lua-users home
lua-l archive

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


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