• Lua print on the same line


    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'	'endend
        write'
    '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.

     
  • 相关阅读:
    XMLHttpRequest 对象相关
    slideToggle()---单击隐藏/浮现--jQuery--click() 方法
    如何打开无线网卡开关(常见无线网卡开关样式)-----记一次令人脸红的羞耻操作
    之前写的页面导出Excel表格
    word 快捷键 部分
    windows 快捷键 部分
    推荐几款屏幕录制工具(可录制GIF)
    【myeclipse2014-2017】使用相关
    嵌套的JsonObject与JSONArray的取值---JSON中嵌套JSONArray
    图片素材库
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3570565.html
Copyright © 2020-2023  润新知