From 9e64b723462544dbc4d64a9179a71fce124018b6 Mon Sep 17 00:00:00 2001 From: David Walter Seikel Date: Thu, 27 Mar 2014 16:17:53 +1000 Subject: Add an example of a C Lua module in the test_c comments. --- ClientHamr/GuiLua/test_c.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) (limited to 'ClientHamr/GuiLua/test_c.c') diff --git a/ClientHamr/GuiLua/test_c.c b/ClientHamr/GuiLua/test_c.c index d72067e..8c3796d 100644 --- a/ClientHamr/GuiLua/test_c.c +++ b/ClientHamr/GuiLua/test_c.c @@ -22,4 +22,57 @@ Though it seems that chapter 26 is not in the same place? http://www.lua.org/pil/26.2.html doesn't say much really, and is for Lua 5.0 + + +An example - + +// build@ gcc -shared -I/home/sdonovan/lua/include -o mylib.so mylib.c +// includes for your code +#include +#include + +// includes for Lua +#include +#include +#include + +// defining functions callable from Lua +static int l_createtable (lua_State *L) { + int narr = luaL_optint(L,1,0); // initial array slots, default 0 + int nrec = luaL_optint(L,2,0); // intialof hash slots, default 0 + lua_createtable(L,narr,nrec); + return 1; +} + +static int l_solve (lua_State *L) { + double a = lua_tonumber(L,1); // coeff of x*x + double b = lua_tonumber(L,2); // coef of x + double c = lua_tonumber(L,3); // constant + double abc = b*b - 4*a*c; + if (abc < 0.0) { + lua_pushnil(L); + lua_pushstring(L,"imaginary roots!"); + return 2; + } else { + abc = sqrt(abc); + a = 2*a; + lua_pushnumber(L,(-b + abc)/a); + lua_pushnumber(L,(+b - abc)/a); + return 2; + } +} + +static const luaL_reg mylib[] = { + {"createtable",l_createtable}, + {"solve",l_solve}, + {NULL,NULL} +}; + +int luaopen_mylib(lua_State *L) +{ + luaL_register (L, "mylib", mylib); + return 1; +} + + */ -- cgit v1.1