Moonshine

How to return values to Lua

Returning primative types

When your Lua code calls a function in the host API, you may return values back into the Lua enviroment. These values are treated differently depending on type.

Strings, numbers and booleans are all passed straight in and treated much as you would expect in Lua.

Undefined is mapped to nil when passed into Lua. Do not use JavaScript Null to repesent nil, it will not work.

All other JavaScript types are treated as userdata when passed into Lua.

Returning tables

To return a table to the Lua environment, you must first create one:

var t = new shine.Table();

Passing an object or array to the constructor will create a new Lua table based on this object.

var t = new shine.Table({ x: 12, y: 34 });
var t2 = new shine.Table([12, 34, 'ab']);

See How to manage tables for more.

Returning multiple values

When your Lua code calls a function in the host API, you may return any number of values. To return multiple values, simply return an array. Returning a single value that is not an array will automatically be treated as an array with a single value.

var foo = { x: 12, y: 34 };

function getPosition () {
	return [foo.x, foo.y];
}

var vm = new shine.VM({ getPosition: getPosition });
vm.load('./lua/my-script.lua.json');
local x, y = getPosition()
print(x, y)	--> 12	34

Should you wish to return an array to Lua, simply wrap that value inside another array. This would, however, return the value to Lua as userdata (see above).