string - 带有嵌入函数的 Lua String [[ .. ]]

标签 string lua

我正在研究如何在 lua 字符串(双括号)中嵌入 lua 函数。只是为了详细说明我的情况:

示例.lua:

function my_message(msg)
    return "Your message: " + msg
end

function makeString()
    page = [[
        <html>
            <body>
<!-- 
        I want to call my_message(..) lua function and embed the value here. 
        What is the best way to achieve this? 
-->
            </body>
        </html>
    ]]
end

提前致谢。

最佳答案

不支持在字符串文字中嵌入值。

或者,您可以拆分字符串并将它们与 my_message 的返回值连接起来,如下所示:

page = [[
    <html>
        <body>
<!-- 
]] ..
assert(load("return '" .. my_message("hello" .. "'")))()
.. [[    
-->
        </body>
    </html>
]]

在 Lua 5.1 中,使用 loadstring 代替 load。另请注意,Lua 使用 .. 连接字符串,而不是像 my_message 中的 +

关于string - 带有嵌入函数的 Lua String [[ .. ]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26173535/

相关文章:

c++ - 如何解析这样的 C++ 输入字符串

lua 命令 lua -e "print("hello") 输出为 nil

尝试编译 lua 文件时出现 gcc 错误

lua - 如何从 Ada 代码控制 win32 中的 cmd 窗口?

c - strtol() 返回不正确的值

javascript - 用 jQuery/JavaScript 替换 , 的最后一个索引

c - 可变长度的字符串到int数组?

compiler-errors - Lua 从 5.1 更新 - LUA_GLOBALSINDEX 问题

redis - PHP Redis Lua 脚本问题

javascript - 任何字符串的正则表达式,它采用 .pdf 之前的所有字符