加载 lua 脚本时出现语法错误

Syntax error when loading lua script

我试图在我的应用程序中使用 lua,但是当我尝试使用 lua_loadBuffer 加载脚本时,我收到一条错误消息。

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 lua 代码有效,对吧? 只是一个 "syntax error" 不是很好描述,我对 lua 没有任何经验,我什至不知道在哪里寻找错误。

Lua 不适用于 UTF-16 字符串。
为确保您的数据使用 1 字节代码页进行编码,请使用 AnsiStringPAnsiChar 而不是 String 和 PChar。