Extrait du course programming in Lua
Lua as a Library
●Lua is implemented as a library
●Exports ~90 functions
●plus ~10 types, ~60 constants, ~20 macros
●functions to run a chunk of code, to call Lua functions, to register C functions to be called by Lua, to get and set global variables, to manipulate tables, etc.
●Stand-alone interpreter is a small client of this library
A Naive Lua Interpreter
#include « lua.h »
#include « lauxlib.h »
#include « lualib.h »
int main (int argc, char **argv) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, argv[1]);
lua_call(L, 0, 0);
lua_close(L);
return 0;
}
Lua Kernel
#include « lua.h »
#include « lauxlib.h »
#include « lualib.h »
int main (int argc, char **argv) {
lua_State*L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, argv[1]);
lua_call(L, 0, 0);
lua_close(L);
return 0;
}
Lua Libraries
#include « lua.h »
#include « lauxlib.h »
#include « lualib.h »
int main (int argc, char **argv) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, argv[1]);
lua_call(L, 0, 0);
lua_close(L);
return 0;
}
The Lua State
●All state of the interpreter stored in a dynamic structure lua_State
●State explicitly created (and destroyed) by the application
●All functions receive a state as first argument
●except function to create a new state
Multiple Lua States
●A state is completely self-contained
●A program can have multiple, independent Lua states
●Allows a lightweight implementation of Lua processes
●each process is a Lua state
●multiple workers (C threads) run those processes
●communication through message passing
Lua Values
●Most APIs use some kind of “Value”type in C to represent values in the language
●PyObject(Python), jobject(JNI)
●Problem: garbage collection
●easy to create dangling references and memory leaks
……..
Programming in Lua course The Lua-C API (132 KO) (Cours PDF)