如何使用布尔变量格式化Lua字符串?
2011-7-7 18:48:46
收藏:0
阅读:198
评论:3
我有一个布尔变量,希望在格式化的字符串中显示其值。我尝试使用 string.format
,但无论在语言参考中选择哪种格式选项,都会得到类似以下的结果:
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print(string.format("%c\n", true))
stdin:1: bad argument #2 to 'format' (number expected, got boolean)
stack traceback:
[C]: in function 'format'
stdin:1: in main chunk
[C]: ?
我可以通过添加 tostring
将布尔显示出来,
> print(string.format("%s\n", tostring(true)))
true
但这对于这个 Lua 新手来说似乎有点间接。我有没有忽略某一种格式选项?或者我应该使用上面的方法?还是其他什么?
原文链接 https://stackoverflow.com/questions/6615572
点赞
stackoverflow用户34799
你可以重定义 string.format
来支持一个额外的 %t
占位符,该占位符会运行 tostring
函数:
do
local strformat = string.format
function string.format(format, ...)
local args = {...}
local match_no = 1
for pos, type in string.gmatch(format, "()%%.-(%a)") do
if type == 't' then
args[match_no] = tostring(args[match_no])
end
match_no = match_no + 1
end
return strformat(string.gsub(format, '%%t', '%%s'),
unpack(args,1,select('#',...)))
end
end
有了这个,你可以使用 %t
对于任何非字符串类型:
print(string.format("bool: %t",true)) -- 输出 "bool: true"
2011-07-13 18:19:49
stackoverflow用户272427
在 Lua 5.1 版本中,当val
不是字符串或数字时,string.format("%s", val)
需要手动使用tostring()
将val
包装起来。
然而在 Lua 5.2 版本中,string.format
会自动调用新的 C 函数luaL_tolstring
,这个函数等同于调用tostring()
来处理val
。
2012-06-01 18:32:27
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
查看
string.format
的代码,我没有发现任何支持布尔值的内容。我猜在这种情况下,使用tostring
是最合理的选项。举个例子:
print("this is: " .. tostring(true)) -- 输出: this is true