Lua ist eine Skriptsprache, welche u.a. in C Programme eingebunden werden kann und somit die Möglichekit bietet, Programmlogik ohne Neukompilierung zu ändern bzw. erweitern. Die Einbindung in ein C-Programm soll dieses Tutorial zeigen.
Installation
Voraussetzung für das Erstellen unf Ausführen von Lua-Skripten - auch von C heraus - sind die folgenden Linux-Module:
- gcc (C-Compiler)
- liblua50-dev (Lua Interpreter)
- liblualib50-dev (Lua Libs und Header)
Eine gute Anleitung zu dem Thema findet sich auch unter http://www.debian-administration.org/articles/264.
Kompilieren
Das Kopilieren und Linken der C-Quellen erfoglt mit dem nachfolgendem Aufruf:
gcc `lua-config --include --libs` -o
Es ist auch möglich, das Lua Skript zu kompilieren. Dazu muss der folgende Befehl ausgeführt werden:
luac -o
Beispiel
Als Beispiel soll ein kleines Programm zur Hashberechnung einer Zeichenkette dienen. Der Aufruf erfolgt aus einem C-Programm (calculatehash.c) heraus.
#include
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
/*
* the function which calls the hash function in the lua script
*/
char* dohash(const char* value)
{
/* the calculated hash value */
char* hash;
/* the lua state */
lua_State* lua_state;
/* init lua state */
L = lua_open();
/* load lua libs */
lua_baselibopen(lua_state);
/* load lua script "hash.lua - stored in the current directory" */
lua_dofile(lua_state, "hash.lua");
/* the name of the function is "hash(x)" */
lua_getglobal(lua_state, "hash");
/* the parameter of the hash function "hash(x)" */
lua_pushstring(lua_state, value );
/* call the hash function with 1 argument and return 1 result */
lua_call(lua_state, 1, 1);
/** convert return value to char* */
hash = (char *)lua_tostring(L, -1);
/** remove from stack */
lua_pop(lua_state, 1);
/* close lua state */
lua_close(lua_state);
/** return the hash value */
return hash;
}
/**
* The main method ...
*/
int main ( int argc, char *argv[] )
{
/** Call the c function and print out the result */
printf("The result is: %sn", dohash(argv[1]));
return 0;
}
Das Lua Skript "hash.lua" - welches im C-Quellcode referenziert wird, enthält die eigentliche Hashfunktion (hier nur eine Dummy-Implementierung):
function hash(x)
return "{implementhash}: " .. x
end
Hier wäre denkbar, einen MD5 oder SHA-1 Hash zu bilden. Dafür sind weitere Lua-Libs notwendig.
Abschliessend muss das C-Programm mit dem folgendem Befehl kompiliert werden:
gcc -Wall `lua-config --include --libs` -o calculatehash calulatehash.c
Das war es schon - wenn jetzt das Programm mit einem Parameter aufgerufen wird, erfolgt die Hashberechnung und das Ergebnis wird auf STDOUT ausgegeben:
ronnyfriedland@dev:~/lua$ ./calculatehash "Hallo Lua"
The result is: {implementhash}: Hallo Lua