/* interp.c : interpreter interface using Lua */ /* * Copyright 2006 Jon Mayo and XXX * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: The above copyright * notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /* You can download Lua at: * http://www.lua.org/ * http://www.tecgraf.puc-rio.br/lua/ */ #include #include #include #include #include #include "interp.h" /** lua functions we're going to define **/ static int echo(lua_State *L) { int nr_arg; int i; nr_arg=lua_gettop(L); for(i=1;i<=nr_arg;i++) { if(lua_isstring(L,i)) { printf("%s",lua_tostring(L,i)); } else { printf("%s:%p",lua_typename(L,lua_type(L,i)),lua_topointer(L,i)); } } printf("\n"); return 0; /* success */ } static lua_State *create_state() { lua_State *L; L=lua_open(); if(L) { luaopen_base(L); luaopen_table(L); luaopen_string(L); /* luaopen_io(L); luaopen_loadlib(L); */ lua_register(L,"echo",echo); } return L; } int interpret_file(const char *filename) { int result; lua_State *L; FILE *f; f=fopen(filename, "r"); if(!f) { perror(filename); return 0; } L=create_state(); result=luaL_loadfile(L, filename); if(!result) { result = lua_pcall(L, 0, LUA_MULTRET, 0); if(result) { fprintf(stderr, "%s:%s\n", filename, lua_tostring(L, -1)); lua_pop(L, 1); } } else { fprintf(stderr, "%s:%s\n", filename, lua_tostring(L, -1)); lua_pop(L, 1); } lua_close(L); fclose(f); return result; } int interpret(const char *name, const char *data) { int data_len; int error; lua_State *L; L=create_state(); data_len=strlen(data); error=luaL_loadbuffer(L,data,data_len,name) || lua_pcall(L, 0, 0, 0); if(error) { fprintf(stderr, "%s", lua_tostring(L, -1)); lua_pop(L, 1); } lua_close(L); return error; }