AP_Scripting: generator: dynamically create userdata metatables

The `luaL_testudata` and `luaL_checkudata` functions correctly treat the
absence of a metatable for the type to check as the type not matching,
so there is no need to have the type's metatable in memory until an
object using it exists. Therefore we can defer the metatable's creation
until the first time an object of that type is created.

Saves some 4500 bytes of Lua heap RAM, at least if no such objects are
created. The created metatables are shared between all scripts, so there
is no increase in the total RAM usage if all objects are used. However,
there is some increased risk of heap fragmentation and unexpected
out-of-memory errors on rarely used code paths.

It would be nice to construct the object in the new utility function,
but it's not possible in C++ to take the address of a constructor.
Instead passing in a lambda is ugly, hardly any more efficient, and
screws up constructors which take parameters.

Also optimizes by using the generated userdata creators where possible,
and convincing the compiler to omit unnecessary checks.
This commit is contained in:
Thomas Watson
2025-12-08 22:01:52 -06:00
committed by Andrew Tridgell
parent 00a2b76779
commit a550087eee
6 changed files with 28 additions and 39 deletions

View File

@@ -507,7 +507,6 @@ void lua_scripts::run(void) {
#endif
lua_atpanic(L, atpanic);
load_generated_bindings(L);
// set up string metatable. we set up one for all scripts that no script has
// access to, as it's impossible to set up one per-script and we don't want