在Lua中更改metatable会破坏冒号运算符 [英] Changing metatable in Lua breaks colon operator

查看:52
本文介绍了在Lua中更改metatable会破坏冒号运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习Lua时,我从此处借了一些代码.使用字符串索引,就是这样:

While learning Lua, I borrowed some code from here to use string indexing, which is exactly this:

getmetatable("").__index = function(str, i) return string.sub(str, i, i) end

在那之后,我编写了一个函数来反向转换字符串.

After that, I wrote a function to reverse a string as practice.

function reverse_string(str)
    local s = ""
    for i = string.len(str), 1, -1 do s = s .. str[i] end
    return s
end

那很好,直到我将 string.len(str)更改为 str:len(),然后出现此错误:

That works fine, until I change the string.len(str) to str:len(), then I get this error:

reverse.lua:9: bad argument #2 to 'sub' (number expected, got string)

调试print()告诉我 __ index 函数正在 str:len()上调用,并且 i 参数变成字符串"len".我知道str:len()可以在其中没有元表的情况下工作,但是一旦添加它,为什么会发生?

Debugging print()'s tell me that the __index function is being called on str:len(), and that the i argument is becoming the string "len". I know that str:len() works without the metatable there, but as soon as I add it this happens, why?

推荐答案

来自卢阿5.2参考手册:字符串操作

字符串库在表字符串中提供了其所有功能.它还在__index字段指向字符串表的地方为字符串设置一个元表.因此,您可以使用面向对象样式的字符串函数.例如,string.byte(s,i)可以写为s:byte(i).

The string library provides all its functions inside the table string. It also sets a metatable for strings where the __index field points to the string table. Therefore, you can use the string functions in object-oriented style. For instance, string.byte(s,i) can be written as s:byte(i).

因此,像 str:len()这样的面向对象样式来自于您已修改的默认元方法 __ index .

So, the object oriented style like str:len() comes from the default metamethod __index, which you have modified.

这篇关于在Lua中更改metatable会破坏冒号运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆