lua中print

reference:

http://www.lua.org/manual/5.3/manual.html

 

print (···)

Receives any number of arguments and prints their values to stdout, using the tostring function to convert each argument to a string. print is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use string.format andio.write.

 

tostring (v)

Receives a value of any type and converts it to a string in a human-readable format. (For complete control of how numbers are converted, usestring.format.)

If the metatable of v has a __tostring field, then tostring calls the corresponding value with v as argument, and uses the result of the call as its result.

示例:

a = {5, 6}
print(a)
--用c来做Metatable
c = {}
c.__tostring =function(set)
    local s = "{" 
    local sep = ""
    for _,e in pairs(set) do
        s = s .. sep .. e
        sep = ", "
    end 
return s .. "}" 
end

setmetatable(a, c)
print(a)

 

执行结果:

table: 0x1041150
{5, 6}

 

注释:

1. 调用第一个打印print(a),表示a为一个table,以及对应的地址。即print 函数调用 tostring 来格式化的输出。

2.调用第二个打印print(a),结果为__tostring的返回值。即当格式化一个对象的时候,tostring 会首先检查对象是否存在一个带有__tostring 域的 metatable。如果存在则以对象作为参数调用对应的函数来完成格式化,返回的结果即为 tostring 的结果。

转载于:https://my.oschina.net/u/2326611/blog/840847

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值