I am working on a project written in C++ which uses Lua as a scripting language. In order to facilitate debugging we implemented a network debugger which receives Lua code, runs it, encodes the return values in Json and sends that string back.
I managed to implement that for tables, but now I am stuck with variables stored in userdata. E.g. I have this Lua code:
Elements.Avatar.testVar = 5
Elements.testVar = 15
return Elements
// result
{
"result0": "{Application:userdata; Avatar:userdata; Physics:userdata; testVar:15; }"
}
Application
, Avatar
and Physics
are objects that have been created in C++. The two testVars
however have been created in the script above.
Elements
is a table, so I can list all elements, but Avatar.testVar
seems to be hidden because Avatar
is a LUA_TUSERDATA
.
Does anyone have an idea how I can detect variables that have been added to userdata in Lua?
There is no such thing as a "variable stored in userdata", At least, not as far as Lua is concerned. From Lua's perspective, userdata is a giant black box. All
Avatar.testVar = 5
does is call the metamethod__newindex
inAvatar
with the stringtestVar
and the new value15
. How your C++ metamethod (because only C++ code can put metamethods on userdata) interprets this is entirely up to your code.So it can't be done from Lua. Your code will need to provide debugging hooks. Lua 5.2 allows you to implement the
__pairs
and__ipairs
metamethods, which thepairs
andipairs
functions can use to iterate over your values. Outside of that, you're on your own for querying what does and doesn't exist in a userdata.