Properly expanding lightuserdata in Lua 5.3.

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Properly expanding lightuserdata in Lua 5.3.

Sleepers Tang
Hi,

I am trying to write a Lua wrapper for my hobby game engine in C++.
Here is the thing.

How could I bind a table to lightuserdata?
I wanna expose a Lua API like this.

local sprite = require "engine.sprite" -- C module
local s = sprite.new() -- returns a C lightuserdata

s.custom_user_defiend_filed = "some value" -- the user may use the lightuserdata like a simple table

After dig a while, I found tolua++ have the setpeer/getpeer which what all I want,
but since Lua 5.3 have removed the setfenv, how could I achieve the same goal?

Thanks in advance. :)





Reply | Threaded
Open this post in threaded view
|

Re: Properly expanding lightuserdata in Lua 5.3.

Andrew Gierth
>>>>> "Sleepers" == Sleepers Tang <[hidden email]> writes:

 Sleepers> Hi,

 Sleepers> I am trying to write a Lua wrapper for my hobby game engine
 Sleepers> in C++. Here is the thing.

 Sleepers> How could I bind a table to lightuserdata?
 Sleepers> I wanna expose a Lua API like this.

 Sleepers> local sprite = require "engine.sprite" -- C module
 Sleepers> local s = sprite.new() -- returns a C lightuserdata

You want that to be a full userdata, not a lightuserdata.

A full userdata with a metatable that defines __index (and __newindex,
__pairs and __len if you want those too) behaves like a table to lua
code; readonly if you only define __index, or writable if you define
__newindex too.

You have a choice: __index and __newindex can be functions, which will
be called to fetch or store values; or you can store an actual lua table
there.

 Sleepers> but since Lua 5.3 have removed the setfenv,

Full userdata in 5.3 have a "uservalue" slot in place of the old
environment table slot; you can store a table there if you need one.
Such a table is not accessible from Lua (unless you provide functions to
access it) but it's a handy place for C functions to store Lua values
that need to be kept associated with the userdata.

--
Andrew.