A loaded chunk is a normal feature. Loading a module from C can be represented as follows:
return (function() -- this is the chunk compiled by load
-- foo.lua
return function (i)
return i
end
end)() -- executed with call/pcall
All you have to do is load the piece and call it, its return value will be your function:
if (luaL_loadstring(L, script)) {
return luaL_error(L, "Error loading script: %s", lua_tostring(L, -1));
}
if (lua_pcall(L, 0, 1, 0)) {
return luaL_error(L, "Error running chunk: %s", lua_tostring(L, -1));
}
lua_pushinteger(L, 42);
if (lua_pcall(L, 1, 1, 0)) {
return luaL_error(L, "Error calling function: %s", lua_tostring(L, -1));
}
source
share