• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Luaprintonthesameline

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

In Pascal, I have write and writeln. Apparently Lua's print is similar to writeln of Pascal. Do we have something similar to write of Pascal? How can consecutive print commands send their output to the same line?

print("Hello")
print("World")

Output:

Hello
world

I want to have this:

Hello world




Use io.write instead print, which is meant for simple uses, like debugging, anyway.

Expanding on lhf's correct answer, the io library is preferred for production use.

The print function in the base library is implemented as a primitive capability. It allows for quick and dirty scripts that compute something and print an answer, with little control over its presentation. Its principle benefits are that it coerces all arguments to string and that it separates each argument in the output with tabs and supplies a newline.

Those advantages quickly become defects when detailed control of the output is required. For that, you really need to use io.write. If you mix print and io.write in the same program, you might trip over another defect. print uses the C stdout file handle explicitly. This means that if you use io.output to change the output file handle, io.write will do what you expect but print won't.

A good compromise can be to implement a replacement for print in terms of io.write. It could look as simple as this untested sample where I've tried to write clearly rather than optimally and still handle nil arguments "correctly":

local write = io.write
function print(...)local n = select("#",...)for i =1,n dolocal v = tostring(select(i,...))
        write(v)if i~=n then write'\t'endend
    write'\n'end

Once you are implementing your own version of print, then it can be tempting to improve it in other ways for your application. Using something with more formatting control than offered by tostring() is one good idea. Another is considering a separator other than a tab character.

 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Lua 之string库发布时间:2022-07-22
下一篇:
Mac系统安装Lua(转)发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap