Mystery Mystery - 4 months ago 15
Pascal Question

Syntax error when loading lua script

Im trying to use lua in my application, but when trying to load a script using lua_loadBuffer, I get an error message.

LuaContext := lua_newstate(@Alloc, nil);
try
luaL_openlibs(LuaContext);
s := 'print("hi")';
lua_register(LuaContext, 'print', @print_func);
if luaL_loadbuffer(LuaContext, PChar(s), Length(s), PChar('sample1')) <> 0 then
begin
raise Exception.Create(lua_tostring(LuaContext, -1)); //<- I get the following error message here: [string "sample1"]:1: syntax error
end;
if lua_pcall(LuaContext, 0, 0, 0) <> 0 then
Exception.Create('');
except
Debugln('Error: ' + lua_tostring(LuaContext, -1));
end;


Afaik the lua code is valid, right?
Just a "syntax error" isn't very descriptive, and me not having any expierience with the lua, I don't even know where to look for mistakes.

Answer

Lua does not work with UTF-16 strings.
To ensure your data is encoded with 1-byte codepage, use AnsiString and PAnsiChar instead of String and PChar.