Garry's Mod Wiki

CompileString

function CompileString( string code, string identifier, boolean HandleError = true )

Description

This function will compile the code argument as lua code and return a function that will execute that code.

Please note that this function will not automatically execute the given code after compiling it.

Arguments

1 string code
The code to compile.
2 string identifier
An identifier in case an error is thrown. (The same identifier can be used multiple times)
3 boolean HandleError = true
If false this function will return an error string instead of throwing an error.

Returns

1 function
A function that, when called, will execute the given code.

Returns the error string if there was a Lua error and third argument is false.

Example

Code that will not compile, with ErrorHandling set to false.

local code = "MsgN('Hi)" local func = CompileString(code, "TestCode", false) MsgN(func)
Output: TestCode:1: unfinished string near '<eof>' (this is not a script error - it is a returned string)

Example

Code that will compile.

local code = "MsgN('Hi')" local func = CompileString(code, "TestCode") if func then -- Compile String returns nil if 3rd argument is true and code has errors. func() end
Output: Hi

Example

Compiled code with custom arguments; captured with the varargs identifier.

local code = [[ local args = { ... } print( unpack( args ) ) print( args[ 2 ] + args[ 3 ]) print( args[ 4 ] .. args[ 5 ]) local first, second = ... print( first, second ) ]] local func = CompileString( code, "VarargCodeTest" ) func( 1, 2, 3, "A", "B", "C" )
Output:
1 2 3 A B C 5 AB 1 2

Page Links


Special Pages


Wikis

?

Render Time: 35ms

DB GetPage 3
Generate Html 8
SaveChanges (1) 10
Render Body 0
Render Sidebar 12