Basic Usage#
Consider the following Moonscript class:
class MyClass
new: (n)=>
@mice = n
add: (n)=>
@mice = @mice + n
"There are now #{@mice} mice!"
Assuming the file is on your package search path, luaC_pushclass()
will be able to find it.
lua_State *L = luaL_newstate();
// need to open Lua libraries before we use moonauxlib.h
luaL_openlibs(L);
luaC_pushclass(L, "MyClass");
// leaves a copy of the class on the stack which can be modified or removed
assert(luaC_isclass(L, -1));
lua_pop(L, 1);
The class can be constructed by name using luaC_construct()
. Its methods can also be called
by name using luaC_mcall()
and luaC_pmcall()
.
lua_pushnumber(L, 6);
luaC_construct(L, 1, "MyClass"); // leaves a MyClass object on the stack
assert(luaC_isobject(L, -1));
assert(luaC_isinstance(L, -1, "MyClass"));
lua_pushnumber(L, 1);
luaC_mcall(L, "add", 1, 1);
moonL_print(L, -1); // prints "There are now 7.0 mice!"
lua_close(L);
return 0;