Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions lualua.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ static const char lualua_host_refname[] =
"github.com/lua-wow-tools/lualua/host";
static const char lualua_sandbox_refname[] =
"github.com/lua-wow-tools/lualua/sandbox";
static const char lualua_debug_metatable[] = "lualua debug";
static const char lualua_state_metatable[] = "lualua state";
static const char lualua_gctoken_metatable[] = "lualua gctoken";

Expand Down Expand Up @@ -214,6 +215,20 @@ static int lualua_getmetatable(lua_State *L) {
return 1;
}

static int lualua_getstack(lua_State *L) {
lualua_State *S = lualua_checkstate(L, 1);
int level = luaL_checkint(L, 2);
lua_Debug *ar = lua_newuserdata(L, sizeof(lua_Debug));
if (lua_getstack(S->state, level, ar)) {
luaL_getmetatable(L, lualua_debug_metatable);
lua_setmetatable(L, -2);
} else {
lua_pop(L, 1);
lua_pushnil(L);
}
return 1;
}

static int lualua_gettable(lua_State *L) {
lualua_State *S = lualua_checkstate(L, 1);
int index = lualua_checkacceptableindex(L, 2, S);
Expand Down Expand Up @@ -754,6 +769,7 @@ static const struct luaL_Reg lualua_state_index[] = {
{"getfield", lualua_getfield},
{"getglobal", lualua_getglobal},
{"getmetatable", lualua_getmetatable},
{"getstack", lualua_getstack},
{"gettable", lualua_gettable},
{"gettop", lualua_gettop},
{"insert", lualua_insert},
Expand Down Expand Up @@ -867,6 +883,12 @@ int luaopen_lualua(lua_State *L) {
lua_settable(L, -3);
}
lua_pop(L, 1);
if (luaL_newmetatable(L, lualua_debug_metatable)) {
lua_pushstring(L, "__metatable");
lua_pushstring(L, lualua_debug_metatable);
lua_settable(L, -3);
}
lua_pop(L, 1);
lua_getfield(L, LUA_REGISTRYINDEX, lualua_host_refname);
if (lua_isnil(L, -1)) {
lua_newtable(L);
Expand Down
16 changes: 16 additions & 0 deletions spec/lualua_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,22 @@ describe('lualua', function()
end)
end)

describe('getstack', function()
it('is nil on bare state', function()
local s = lib.newstate()
local d = s:getstack(0)
assert.Nil(d)
end)
it('works inside a pushcfunction', function()
local s = lib.newstate()
s:pushcfunction(function(ss)
local d = ss:getstack(0)
assert.same('userdata', type(d))
end)
s:call(0, 0)
end)
end)

describe('gettable', function()
it('fails on empty stack', function()
local s = lib.newstate()
Expand Down