tim

small extendable personal assistant
git clone git://edryd.org/tim
Log | Files | Refs | LICENSE

tim-lua.c (1137B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 #include "lua5.3/lua.h"
      6 #include "lua5.3/lualib.h"
      7 #include "lua5.3/lauxlib.h"
      8 
      9 #include "util.h"
     10 #include "tim.h"
     11 #include "tim-lua.h"
     12 
     13 static int
     14 tim_lua_get_path(lua_State *L)
     15 {
     16 	const char *fname = luaL_checkstring(L, 1);
     17 
     18 	lua_pushstring(L, get_path(fname));
     19 
     20 	return 1;
     21 }
     22 
     23 char *
     24 tim_lua_run(char *script, char *args)
     25 {
     26 	char *ret = NULL;
     27 	lua_State *L;
     28 
     29 	/* init script */
     30 	L = luaL_newstate();
     31 	luaL_openlibs(L);
     32 	if (luaL_loadfile(L, script))
     33 		die("tim_lua: couldn't load file: %s\n", lua_tostring(L, -1));
     34 
     35 	/* add variables */
     36 	lua_pushstring(L, args);
     37 	lua_setglobal(L, "args");
     38 
     39 	/* add functions */
     40 	lua_pushcfunction(L, tim_lua_get_path);
     41 	lua_setglobal(L, "get_path");
     42 
     43 	/* run script */
     44 	if (lua_pcall(L, 0, LUA_MULTRET, 0))
     45 		die("tim_lua: failed to run script: %s", lua_tostring(L, -1));
     46 
     47 	/* get the returned value */
     48 	const char *tmp = lua_tostring(L, -1);
     49 	if (tmp)
     50 		ret = strdup(tmp);
     51 	lua_pop(L, 1); /* take the returned value out of the stack */
     52 
     53 	/* cleanup */
     54 	lua_close(L);
     55 
     56 	return ret;
     57 }