1 #include <stdlib.h>
2 
3 #include <lua.h>
4 #include <lauxlib.h>
5 #include <lualib.h>
6 
7 #include "image.h"
8 #include "path.h"
9 
10 char __cdecl *realpath( const char *__restrict__ name, char *__restrict__ resolved );
11 
luamain(lua_State * L)12 static int luamain( lua_State* L )
13 {
14   int          argc = (int)lua_tonumber( L, lua_upvalueindex( 1 ) );
15   const char** argv = (const char**)lua_touserdata( L, lua_upvalueindex( 2 ) );
16   int          i;
17 
18   if ( argc < 2 )
19   {
20     return luaL_error( L, "Lua file missing\n" );
21   }
22 
23   if ( luaL_loadfile( L, argv[ 1 ] ) != LUA_OK )
24   {
25     return luaL_error( L, "%s", lua_tostring( L, -1 ) );
26   }
27 
28   lua_call( L, 0, 1 );
29 
30   lua_newtable( L );
31 
32   {
33     char  buffer[ _MAX_PATH ];
34     char* resolved = realpath( argv[ 1 ], buffer );
35 
36     lua_pushstring( L, resolved ? resolved : argv[ 1 ] );
37     lua_rawseti( L, -2, 0 );
38   }
39 
40   for ( i = 2; i < argc; i++ )
41   {
42     lua_pushstring( L, argv[ i ] );
43     lua_rawseti( L, -2, i - 1 );
44   }
45 
46   lua_call( L, 1, 1 );
47   return (int)lua_tointeger( L, -1 );
48 }
49 
traceback(lua_State * L)50 static int traceback( lua_State* L )
51 {
52   luaL_traceback( L, L, lua_tostring( L, -1 ), 1 );
53   return 1;
54 }
55 
main(int argc,const char * argv[])56 int main( int argc, const char *argv[] )
57 {
58   lua_State* L = luaL_newstate();
59   int        top;
60 
61   if ( L )
62   {
63     top = lua_gettop( L );
64     luaL_openlibs( L );
65     luaL_requiref( L, LUA_IMAGELIBNAME, luaopen_image, 0 );
66     luaL_requiref( L, LUA_PATHLIBNAME, luaopen_path, 0 );
67     lua_settop( L, top );
68 
69     lua_pushcfunction( L, traceback );
70 
71     lua_pushnumber( L, argc );
72     lua_pushlightuserdata( L, (void*)argv );
73     lua_pushcclosure( L, luamain, 2 );
74 
75     if ( lua_pcall( L, 0, 1, -2 ) != 0 )
76     {
77       fprintf( stderr, "%s\n", lua_tostring( L, -1 ) );
78     }
79 
80     top = (int)lua_tointeger( L, -1 );
81     lua_close( L );
82     return top;
83   }
84 
85   fprintf( stderr, "could't create the Lua state\n" );
86   return 1;
87 }
88