Generally, the following steps are required to call a Lua function:
// 1. parse the function name and apply the Lua function to the stack.
Findluaitem ( " A. B. C. func " );
// 2. Parameter pressure Stack
Lua_push ()
// 3. function call
Lua_call ()
The slowest process is the first step to parse the function name and repeat the table. This process consumes a lot of time and space.
If this process can be avoided, the efficiency can be improved.
A function always has a function pointer. Even if the Lua function does not exist, you should have a handler. This idea is confirmed in luabind, and he uses an int as the handle of the Lua function.
Next, I looked at the Lua SDK and didn't find the API that returned the Lua function handle. So I thought of this idea: Use a table to save the Lua function that needs to be called. The table key is the handle of the Lua function.
Customtable [handler] = A. B. C. func
To access a Lua table in C, you need to index the table. At that time, I only thought of lua_globalsindex. Later I learned from my classmates that there were lua_environindex and lua_registryindex. After consideration, I think the Registry table is the most suitable.
Lua provides a registry, a pre-defined table that can be used by any C code to store whatever Lua value it needs to store. this table is always located at Pseudo-index lua_registryindex. any C library can store data into this table, but it shoshould take care to choose keys different from those used by other libraries, to avoid collisions. typically, you should use as key a string containing your library name or a light userdata with the address of a C object in your code.
Save the Lua function to this table. Lua provides an API for adding entries in the table, lual_ref. The returned value is the key and an integer of the new entry. In this way, everything is ready.
ProgramIn the initialization phase, assign a handle to all called Lua functions:
1 Findluaitem ("A. B. C. func " );
2 Int Handler = Lual_ref (L, lua_registryindex );
Call the Lua function later:1//Apply the Lua function to the stack
2Lua_rawgeti (L, lua_registryindex, Handler );
3
4Lua_push ();
5Lua_call ();
That is it