You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.5 KiB
C

/*
* 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 = luaL_newstate();
/* Load necessary libs. */
luaL_Reg lualibs[] = {
{ "base", luaopen_base },
{ "string", luaopen_string },
{ NULL, NULL}
};
for (luaL_Reg *lib = lualibs; lib->func; lib++) {
printf("Loading %s\n", lib->name);
lib->func(L);
lua_setglobal(L, lib->name);
lua_settop(L, 0);
}
/* Alternatively, we could have called LuaL_openlibs(L) but that would have
loaded *all* libs. */
/* 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);
}