gpt4 book ai didi

Lua - 为什么允许函数调用后的字符串?

转载 作者:行者123 更新时间:2023-12-04 17:31:16 28 4
gpt4 key购买 nike

我正在尝试实现一个简单的 C++ 函数,它检查 Lua 脚本的语法。为此,我使用 Lua 的编译器函数 luaL_loadbufferx()并在之后检查其返回值。

最近,我遇到了一个问题,因为我认为应该标记为无效的代码没有被检测到,而是脚本稍后在运行时失败(例如在 lua_pcall() 中)。

示例 Lua 代码(可以在 official Lua demo 上测试):

function myfunc()
return "everyone"
end

-- Examples of unexpected behaviour:
-- The following lines pass the compile time check without errors.
print("Hello " .. myfunc() "!") -- Runtime error: attempt to call a string value
print("Hello " .. myfunc() {1,2,3}) -- Runtime error: attempt to call a string value

-- Other examples:
-- The following lines contain examples of invalid syntax, which IS detected by compiler.
print("Hello " myfunc() .. "!") -- Compile error: ')' expected near 'myfunc'
print("Hello " .. myfunc() 5) -- Compile error: ')' expected near '5'
print("Hello " .. myfunc() .. ) -- Compile error: unexpected symbol near ')'

目标显然是在编译时捕获所有语法错误。所以我的问题是:
  • 调用字符串值究竟是什么意思?
  • 为什么首先允许这种语法?是一些我不知道的 Lua 特性,还是 luaL_loadbufferx()在这个特定的例子中是错误的吗?
  • 是否可以通过任何其他方法检测此类错误而不运行它?不幸的是,我的函数在编译时无法访问全局变量,所以我不能直接通过 lua_pcall() 直接运行代码。 .

  • 注意:我使用的是 Lua 版本 5.3.4 ( manual here )。

    非常感谢您的帮助。

    最佳答案

    两者 myfunc() "!"myfunc(){1,2,3}是有效的 Lua 表达式。

    Lua 允许调用 exp 字符串形式。见 functioncallprefixexpSyntax of Lua .

    所以myfunc() "!"是一个有效的函数调用,它调用任何 myfunc返回并用字符串 "!" 调用它.

    对于 exp table-literal 形式的调用,也会发生同样的事情。

    关于Lua - 为什么允许函数调用后的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44976924/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com