diff --git a/.gitignore b/.gitignore index b022ebb..7f74da5 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ multibrot multibrot.png bloom wo-lernen +lua-foo diff --git a/Makefile b/Makefile index 2a267a7..6be883f 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ CFLAGS=-std=c99 -Wall -g -O2 INDENTOPTS=-kr --no-tabs --braces-on-func-def-line --indent-level2 -TARGETS=approximate-pi linked-list mandelbrot threads circular-buffer structs ncurses-pong bit-fuckery bit-fuckery2 checkcheck multibrot bloom wo-lernen +TARGETS=approximate-pi linked-list mandelbrot threads circular-buffer structs ncurses-pong bit-fuckery bit-fuckery2 checkcheck multibrot bloom wo-lernen lua-foo EXTRAS=mandelbrot.bmp multibrot.png .PHONY: all @@ -31,3 +31,6 @@ multibrot: multibrot.c multibrot.png: multibrot ./multibrot -j2 + +lua-foo: lua-foo.c + $(CC) $(CFLAGS) -o $@ $< -llua -lm diff --git a/lua-foo.c b/lua-foo.c new file mode 100644 index 0000000..7457454 --- /dev/null +++ b/lua-foo.c @@ -0,0 +1,61 @@ +/* + * Based on: + * + * http://heavycoder.com/tutorials/lua_embed.php + * http://www.lua.org/pil/26.html + * http://cc.byexamples.com/2008/06/07/how-to-embed-lua-51-in-c/ + * + */ + +#include +#include +#include + +#include +#include +#include + +#include + +void error(lua_State *L, const char *fmt, ...) { + va_list argp; + va_start(argp, fmt); + vfprintf(stderr, fmt, argp); + va_end(argp); + lua_close(L); + exit(EXIT_FAILURE); +} + +/* Provided to Lua as 'mysin' later. */ +static int l_mysin(lua_State *L) { + double d = luaL_checknumber(L, 1); /* get argument */ + + lua_pushnumber(L, sin(d)); /* push result */ + return 1; /* number of results */ +} + +int main(void) { + /* Set up Lua. */ + lua_State *L; + L = lua_open(); + + luaopen_base(L); + luaopen_string(L); + /* Alternatively: + luaL_openlibs(L); */ + + /* Register 'mysin'. */ + lua_pushcfunction(L, l_mysin); + lua_setglobal(L, "mysin"); + + /* Load and run Lua file. */ + const char* filename = "lua-foo.lua"; + if (luaL_loadfile(L, filename) || lua_pcall(L, 0, 0, 0)) + error(L, "cannot run file: %s\n", lua_tostring(L, -1)); + + /* Clean up. */ + lua_close(L); + + /* Quit. */ + exit(EXIT_SUCCESS); +} diff --git a/lua-foo.lua b/lua-foo.lua new file mode 100644 index 0000000..4376a5b --- /dev/null +++ b/lua-foo.lua @@ -0,0 +1,6 @@ +-- foo() +for x = 0.00, 3.14, 0.20 do + print(string.format("mysin(%03.2f) = %03.2f", x, mysin(x))) + + -- mysin("foo") +end