CompileString

From Garry's Mod
Jump to: navigation, search
 CompileString( )

Contents

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

string code

The code to compile.

Arguments

string identifier

An identifier in case an error is thrown. (The same identifier can be used multiple times)

Arguments

boolean HandleError=true

If false this function will return an error string instead of throwing an error.

Returns

function

A function that, when called, will execute the given code. Returns nil if there was an error.

Returns

string

The error string. Will be nil if there were no errors or the function handles errors (third argument is true).

Examples

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)

Examples

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


Examples

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
Personal tools
Navigation