Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass large struct back and forth between between C++ and Lua

Tags:

c++

lua

I am looking at embedding Lua in a C++ application I am developing. My intention is to use Lua to script what ordered operation(s) to perform for some given input, ie. receive a new work item in c++ program, pass details to Lua backend, Lua calls back into c++ to carry out necessary work, returns finished results.

The primary data structure involved is a large (approx 80+ members) struct. I am (very) new to Lua and am unsure of how I can pass it to and from my host application and the embedded Lua state.

Thus far I see my options as:

a) Pushing/Popping all the individual data members onto the stack when crossing to/from C++ and Lua (sounds messy).

b) Constructing a table and populating with the values, then putting that on/off the stack (a little cleaner).

c) Pass it as userdata (light/heavy?) (I'm sketchy on this, and not sure if/how I can then access it from the Lua side to query what operations are necessary).

Any guidance would be greatly appreciated.

like image 581
Dunni Avatar asked Nov 12 '08 04:11

Dunni


1 Answers

If I recall correctly, light userdata is actually just a pointer. They all share the same metatable. They are mostly used to pass around addresses of C data.
Full userdata is probably closer of what you need if you must access it from the Lua side. Their metatable would allow you to access it like it was a regular Lua table, for example.

You might be also interested by Roberto's library for converting data to and from C structs for Lua 5.1. Or not. Depends on your needs... :-)

like image 98
PhiLho Avatar answered Oct 24 '22 15:10

PhiLho