Lua Userdata with user data

Sometimes I play around with Lua, and recently I decided it’s time to learn how to write modules in C/C++. I implemented a simple userdata with a few methods and property getter/setters. And while writing the Lua script to test the module, I noticed you could not set arbitrary properties on the userdata (of course not, it’s a userdata not a table). Then I started investigating, how this might be achived, yet every time I thought I had a solution it turned out it wouldn’t work, for some reason or other…

I was just about to give up, when I noticed a simple little paragraph in the Lua docs:

Pops a table from the stack and sets it as the new environment for the value at the given index. If the value at the given index is neither a function nor a thread nor a userdata, lua_setfenv returns 0. Otherwise it returns 1.

http://www.lua.org/manual/5.1/manual.html#lua_setfenv

I knew about this function and its getter equivalent (lua_getfenv) but always assumed the “f” in the name stood for “function”. I have no idea what it might stand for, but once the implication of the emphasized part hit me, it became clear! Every userdata can have its own environment table! And with two simple metatable functions for “__index” and “__newindex”, this environment table can be exposed to the Lua side and user properties/methods could be set!

And just after I had it implemented, I found a page in the lua-users wiki where it shows how to do just that (although it is not the main focus on the page)… I hate when that happens. :-(

Advertisements