1
votes

I want to add some static fields to my Lua userdata objects coming from C++. The objects in question are vectors, they're created in C++ land and they work as they are but I've tried lua_setfield on my userdata but I get a attempt to index a Vector value error and I don't really want to have to use .x(), .y(), .z() due to the cost of having to call a function, push to stack and then read on the Lua side.

Is there any way to register fields on userdata for Lua access?

1

1 Answers

0
votes

Userdata doesn't have "fields". What it can have is a metatable, for which you can define the __index and __newindex metamethods. Given such a metatable, the former function is called when reading the value of a field of the userdata, while the latter is called when assigning a value to a field from the outside (ud.some_field = 4 or an equivalent). If you want fields to be read only (to some degree), you can just implement __index, and attempts by the user to use __newindex will fail.

So in your C++ code, after creating the userdata, you can use lua_setmetatable to assign it a table that has these methods defined within it. Of course, these functions will need to access the actual C++ object from the userdata and fetch the specific values you're interested in.