add lua experiment
parent
19ad87265b
commit
6518f586b2
@ -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 <stdarg.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include <lua.h>
|
||||
#include <lualib.h>
|
||||
#include <lauxlib.h>
|
||||
|
||||
#include <math.h>
|
||||
|
||||
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);
|
||||
}
|
@ -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
|
Loading…
Reference in New Issue