Skip to content

Instantly share code, notes, and snippets.

@graphitemaster
Last active March 8, 2017 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphitemaster/ea15ce60f04b63772bc0420f5ed59744 to your computer and use it in GitHub Desktop.
Save graphitemaster/ea15ce60f04b63772bc0420f5ed59744 to your computer and use it in GitHub Desktop.
int trace(lua_State* L) {
if (!lua_isstring( L, 1 )) return 1;
lua_getglobal(L, "debug");
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
return 1;
}
lua_getfield(L, -1, "traceback");
if (!lua_isfunction(L, -1)) {
lua_pop(L, 2);
return 1;
}
lua_pushvalue(L, 1);
lua_pushinteger(L, 2);
lua_call(L, 2, 1);
return 1;
}
bool run(lua_State* L, int args, int results) {
int base = lua_gettop(L) - args;
lua_pushcfunction(L, trace);
lua_insert(L, base);
int status = lua_pcall(L, args, results, base);
lua_remove(L, base);
if (status != 0) {
error(lua_tostring(L, -1));
return false;
}
return true;
}
int main() {
// some lua state setup here
luaL_loadfile(L, "b.lua");
run(L, 0, LUA_MULTRET);
luaL_loadfile(L, "c.lua");
run(L, 0, LUA_MULTRET);
}
local a = { }
a.x = 0
a.y = 0
a.z = 0
a.__index = a
function a:new(x, y, z)
return setmetatable( { x = x, y = y, z = z }, a )
end
a.foo = a:new(1, 2, 3)
return setmetatable(a, { __call = function(self, ...) return a:new(...) end } )
local a = require 'a'
print(a.foo.x) -- prints 1
print(a.foo.y) -- prints 2
print(a.foo.z) -- prints 3
local a = require 'a'
print(a.foo.x) -- prints 1
print(a.foo.y) -- prints 2
print(a.foo.z) -- prints <random garbage value>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment