Lua bindings: table vs userdata

When creating Lua bindings for C ++ classes, should I return tables or userdata objects?

Does anyone know any pros and cons for each method?

+3
source share
1 answer

I recommend returning user data. Regardless of the approach, you need to place a pointer somewhere to the data in C ++ or the actual C ++ data, and there it is nowhere safe to do this with a table.

Returned tables would make sense in some situations, as they can be โ€œannotatedโ€ in Lua with additional attributes without having to do anything extra to support this. Unfortunately, a pointer to a C ++ object must go somewhere, and nowhere is it wise to go other than the actual record in the table itself.

This is not a very safe place to do this. It can be found in the Lua code, and also removed or replaced. It may be random or purpose, it does not really matter.

Therefore, I prefer to return userdata objects. They can be designed to work like tables, if you really need to insist on it, but they also have a "secret" area (user data itself), where the C ++ object pointer can be saved, protected from being overwritten by Lua code.

( Userdata "", , . userdata Lua .)

+6

Source: https://habr.com/ru/post/1717867/


All Articles