lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Mon, Aug 13, 2012 at 10:26 PM, Francisco Tolmasky <tolmasky@gmail.com> wrote:
> There are a few "small" object types that I need to occasionally pass over to the C side of things. For example, lets say a Point class (containing x and y). These points get used internally by the C code to do graphics stuff, etc (or say Quaternions, etc.). The point is, I'm referring to simple objects that you might use a struct for, would rarely have a pointer for in C or a non-trivial lifetime like an "Image" class or something. I've devised two strategies:
>
> 1. Create a traditional userdata-style object that I expose to Lua. So I have like struct Point { float x; float y; }, some functions that I luaL_register etc. So basically anytime you do anything with a point (add two together, access its members, etc) it jumps over to C. I get the impression this is what a lot (most?) people do in these situations.
>
> 2. Create the object as a traditional table in lua code, then when I need something in C, operate on the table. So for example, I'll have a table with x and y keys in Lua, then when I pass it to one of the graphics library functions, it checks its metatable to make sure its the right kind of object (or maybe even just check that it has number x and y), and use whatever it needs from it. Similarly, when I need to return a point from C, I actually create the table (or load a chunk that calls the "constructor" defined in Lua).
>
> So basically, either dealing with a C exposed object in Lua, or dealing with a Lua table in C.
>
> I'm new to Lua so I'm not sure if one is obviously better than the other. I would personally prefer to do as much in Lua as possible (avoiding compiles, interaction with the runtime, etc). I suspect that crossing the C barrier often is slow too (especially if I'm not doing it to do something super efficiently in C). But perhaps there's some performance characteristic I'm not realizing.
>
> Any suggestions, gotchas, etc?
>
> Thanks!
>
> Francisco
>

My first recommendation given your use case is to consider using
LuaJIT if it's available for your platform. You can then use your
struct definitions directly from Lua code (point.x and point.y work
exactly as you would expect), and LuaJIT will perform a LOT better
than vanilla Lua.

The main caveats are that LuaJIT follows Lua 5.1, not 5.2, and it's
not available on as many platforms as vanilla Lua due to the need to
maintain per-platform low-level assembly code. (There's also a problem
on Mac x64 if you can't change the linker flags on the host
application; this is a kernel-level problem that can't be fixed in
LuaJIT. Fortunately, if you control the host application, all is
happy.)

/s/ Adam