ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.18k stars 515 forks source link

Unique table identifier? #1555

Open UltraEngine opened 10 months ago

UltraEngine commented 10 months ago

I am writing some code to convert a sol::table into a C++ structure, and I want to prevent infinite recursive loops from forming when a table has itself somewhere in one of its own keys, or in the sub-structure.

What can I use as a unique identifier for the table? I tried registry_index() but I thing this value changes as I am traversing through the data...

UltraEngine commented 10 months ago

Maybe sol::table::pointer does this?

Rochet2 commented 10 months ago

Not 100% sure, but fairly sure there is no unique value you can get from the lua API. You would need to compare the values using lua equality operation to determine if two tables are equal (lua_rawequal). You can then generate a running number yourself to keep track of the references.

Another way is to instead keep track of the data in lua. With a lua table you can store the table itself as the key and then later when you want to check if a table was already seen, you just look it from the table (example).

A quick and dirty alternative might be to use tostring() on the table. This will return a string similar to table: 0x1b85730 where the value is the address of the table I recon. However, a table can override the tostring operation with a metafield __tostring.