通常調用一個lua函數需要以下步驟
最慢的是第一步解析函數名、反復查表的過程,這個過程會消耗不少時間和空間。如果可以避開這個過程,就能提升效率。函數總有函數指針,就算lua函數沒有,也該有個handler吧。這個想法在LuaBind中得到了確認,他用一個int做lua函數的句柄。接下來看了看lua SDK,沒有發現返回lua函數句柄的API,于是想到了這個點子:用一個表保存需要調用的lua函數,表的key就是lua函數的句柄。CustomTable[ handler ] = a.b.c.func在C中訪問lua的表,需要表索引。當時想到的只有LUA_GLOBALSINDEX,后來從同學那知道還有LUA_ENVIRONINDEX和LUA_REGISTRYINDEX。考慮了一下,覺得registry表最合適。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 should 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.要將lua函數保存到這個表。lua提供了在表里增加一個條目的API,luaL_ref,返回值是新條目的key,一個整數。這樣就萬事俱備了。程序初始化階段,給所有會調用的lua函數分配句柄: