Question

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?

Was it helpful?

Solution

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 in Avatar with the string testVar and the new value 15. 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 the pairs and ipairs 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top