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.

62 lines
1.2 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 = 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);
}