Lua中調(diào)用C語言函數(shù)實例
在上一篇文章(C調(diào)用lua函數(shù))中,講述了如何用c語言調(diào)用lua函數(shù),通常,A語言能調(diào)用B語言,反過來也是成立的。正如Java與c語言之間使用JNI來互調(diào),Lua與C也可以互調(diào)。
當lua調(diào)用c函數(shù)時,使用了和c調(diào)用lua中的同一種棧,c函數(shù)從棧中得到函數(shù),然后將結(jié)果壓入棧中。為了區(qū)分返回結(jié)果和棧中的其他值,每一個函數(shù)返回結(jié)果的個數(shù)。
這里有個重要的概念:這個棧不是全局的結(jié)構(gòu),每個函數(shù)都有自己的私有局部棧。哪怕c函數(shù)調(diào)用了lua代碼,lua代碼再次調(diào)用該c函數(shù),他們有各自獨立的局部棧。第一個參數(shù)的索引是1。
作為第一個例子,讓我們看看如何實現(xiàn)一個簡單的函數(shù),返回給定2個參數(shù)的和:
static int l_plus(lua_State* L)
{
lua_Integer a = lua_tointeger(L, 1);
lua_Integer b = lua_tointeger(L, 2);
lua_pushinteger(L, a+b);
return 1;
}
每一個Lua注冊的函數(shù)都必須是這個原型,它已經(jīng)在lua.h中定義了:
typedef int (*lua_CFunction) (lua_State *L);
由于c函數(shù)返回了一個int類型的返回值個數(shù)。因此,當壓入返回值之前,不必要清理棧,lua會自動移除返回值下面的任何數(shù)據(jù)。
在lua中使用該函數(shù)之前,我們需要注冊它。使用lua_pushcfunction,它接受一個c函數(shù),然后在lua內(nèi)部創(chuàng)建一個函數(shù)類型的值來表示該函數(shù)。
lua_pushcfunction(L, lua_plus);
lua_setglobal(L, "myplus");
一個專業(yè)點的寫法是,我們必須檢查它的參數(shù)類型:
static int l_plus(lua_State* L)
{
lua_Integer a = luaL_checkinteger(L, 1);
lua_Integer b = luaL_checkinteger(L, 2);
lua_pushinteger(L, a+b);
return 1;
}
完整代碼:
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static int l_plus(lua_State* L)
{
lua_Integer a = luaL_checkinteger(L, 1);
lua_Integer b = luaL_checkinteger(L, 2);
lua_pushinteger(L, a+b);
return 1;
}
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, l_plus);
lua_setglobal(L, "myplus");
if (luaL_dostring(L, "print(myplus(2,2))")) {
lua_close(L);
error("Failed to invoke");
}
lua_close(L);
return 0;
}
(完)
相關(guān)文章
使用lua實現(xiàn)php的print_r()函數(shù)功能
筆者比較熟悉php,所以一直在做一些使用lua來實現(xiàn)php中函數(shù)的功能,算是自己對lua理解的一個小測試吧2014-11-11Lua獲取網(wǎng)絡(luò)時間(獲取時間同步服務器的時間)
這篇文章主要介紹了Lua獲取網(wǎng)絡(luò)時間(獲取時間同步服務器的時間),本文使用Lua作為客戶端獲取網(wǎng)絡(luò)上的一些授時服務提供商的時間,需要的朋友可以參考下2015-04-04