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