Dies ist eine alte Version des Dokuments!
Durch das Einbetten von Lua in eine C-Applikation kann die Funktionalität der Applikation wesentlich beeinflusst werden. Von grossem Vorteil ist, dass die Erstellung des Lua-Codes high-level und ohne komplexe Entwicklungsumgebung vorgenommen werden kann. Spezielle Kenntnisse von C/C++ sind hierfür nicht erforderlich.
Im Beispiel hier soll eine Berechnungsfunktion in ein Lua-Script ausgelagert werden. Im File main.c sind die einzelnen Schritte kommentiert.
// Source: https://nicolasgoles.com/blog/2013/01/lua-tutorial-c-bindings/
// Some changes: Claus Kuehnel 2015-01-30
#include <assert.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
int main() {
printf("C : Starting the C-Application\n");
printf("C : Preparing the stack and call Lua\n");
// Create new Lua state and load the lua libraries
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// Tell Lua to load & run the file sample_script.lua
luaL_dofile(L, "sample_script.lua");
// Push "sum" function to the Lua stack
lua_getglobal(L, "sum");
// Checks if top of the Lua stack is a function.
assert(lua_isfunction(L, -1));
// Let's push two numbers to the sum function
int a = 19;
int b = 1;
lua_pushnumber(L, a); // push a to the top of the stack
lua_pushnumber(L, b); // push b to the top of the stack
// Perform the function call (2 arguments, 1 result) */
if (lua_pcall(L, 2, 1, 0) != 0) {
printf("Error running function f:%s`", lua_tostring(L, -1));
}
// Let's retrieve the function result
// Check if the top of the Lua Stack has a numeric value
if (!lua_isnumber(L, -1)) {
printf("Function `sum' must return a number");
}
double c = lua_tonumber(L, -1); // retrieve the result
lua_pop(L, 1); // Pop retrieved value from the Lua stack
// Close the Lua state
lua_close(L);
printf("C : Closing Lua\n");
printf("C : The number returned by sum is %f\n", c);
printf("C : Closing C\n");
return 0;
}