unit DEngLua;

{$MODE FPC}
{$MODESWITCH DEFAULTPARAMETERS}
{$MODESWITCH OUT}
{$MODESWITCH RESULT}

interface

uses
  lua,
  dfilereader,
  dansiview,
  DEng;

function LuaLoadString(L: Plua_State; Path: TAnsiView; Source: PAnsiChar): Boolean;

function LuaLoadFile(L: Plua_State; FileName: TAnsiView): Boolean;

function LogPCall(L: Plua_State; Name: TAnsiView; Res: lua_Integer): Boolean;

function LuaPCall(L: Plua_State; Name: TAnsiView): Boolean; inline;

implementation

function LuaLoadString(L: Plua_State; Path: TAnsiView; Source: PAnsiChar): Boolean;
begin
  case luaL_loadstring(L, Source) of
    LUA_OK: Exit(True);
    LUA_ERRSYNTAX: Log('ERROR ' + Path.ToString + ': ' + lua_tostring(L, lua_gettop(L)));
    LUA_ERRMEM: Log('ERROR ' + Path.ToString + ': out-of-memory');
    LUA_ERRGCMM: Log('ERROR ' + Path.ToString + ': __gc failed');
  else
    Log('ERROR ' + Path.ToString + ': unexpected parsing result');
  end;
  Exit(False);
end;

function LuaLoadFile(L: Plua_State; FileName: TAnsiView): Boolean;
var
  Content: AnsiString;
begin
  if not ReadFileContent(FileName.ToString, Content) then begin
    Log('Could not read ' + FileName.ToString);
    Exit(False);
  end;
  Exit(LuaLoadString(L, FileName, @Content[1]));
end;

function LogPCall(L: Plua_State; Name: TAnsiView; Res: lua_Integer): Boolean;
begin
  case Res of
    LUA_OK: Exit(True);
    //LUA_YIELD: goto L_REPEAT;
    LUA_ERRRUN:  Log('ERROR ' + Name.ToString + ': ' + lua_tostring(L, lua_gettop(L)));
    LUA_ERRMEM:  Log('ERROR ' + Name.ToString + ': out-of-memory');
    LUA_ERRERR:  Log('ERROR ' + Name.ToString + ': error while running message handler');
    LUA_ERRGCMM: Log('ERROR ' + Name.ToString + ': __gc failed');
  else
    Log('ERROR ' + Name.ToString + ': unexpected runtime result');
  end;
  Exit(False);
end;

function LuaPCall(L: Plua_State; Name: TAnsiView): Boolean;
begin
  Result := LogPCall(L, Name, lua_pcall(L, 0, LUA_MULTRET, 0));
end;

end.
