如何從 C 語言呼叫 Lua 函式?
從 C 語言呼叫 Lua 函式需要一系列步驟,並且需要掌握 Lua 庫函式。無論何時我們想要從 C 語言呼叫 Lua 函式或反之,Lua 都提供了幾個庫函式供我們使用。
以下是一些從 C 語言呼叫 Lua 函式最常用的 Lua 庫函式:
- luaL_dofile(L, "myFile.lua");
- lua_getglobal(L, "add");
- lua_pushnumber(L, a);
等等。
當我們從 C 語言呼叫 Lua 函式時,我們將使用這些函式。
第一步是關閉 Lua 直譯器,為此我們需要在 C 語言中編寫程式碼。
示例
請考慮以下示例:
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int main(int argc, char *argv[]) {
lua_State* L;
L = luaL_newstate();
luaL_openlibs(L);
lua_close(L);
printf( "Press enter to exit..." );
getchar();
return 0;
}現在,我們只需要為包含我們將從 C 程式碼中呼叫的 Lua 程式碼的檔案呼叫 luaL_dofile(L, "myFile.lua"); 函式。
請考慮以下程式碼,它寫在 myFile.lua 中:
add = function(a,b) return a + b end
現在,將呼叫上述 Lua 函式的 C 檔案將如下所示:
int luaAdd(lua_State* L, int a, int b) {
// Push the add function on the top of the lua stack
lua_getglobal(L, "add");
// Push the first argument on the top of the lua stack
lua_pushnumber(L, a);
// Push the second argument on the top of the lua stack
lua_pushnumber(L, b);
// Call the function with 2 arguments, returning 1 result
lua_call(L, 2, 1);
// Get the result
int sum = (int)lua_tointeger(L, -1);
lua_pop(L, 1);
return sum;
}當我們在 C 語言中呼叫此 luaAdd() 函式時,輸出將為:(對於 a = 2,b = 3)
5
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP