【问题标题】:Lua How to create custom function that can be used on variables follow upLua 如何创建可用于变量后续的自定义函数
【发布时间】:2015-01-31 11:00:11
【问题描述】:

跟进我之前的问题(此处链接:Lua How to create custom function that can be used on variables?),有没有办法创建适用于表格以外的其他事物的相同类型的函数?例如,

str = "stuff"
letter = str:foo() --Maybe have the foo function extract the first letter?

有没有办法创建一个以相同方式工作的函数

lowerCasestr = str:lower()

有效吗?

【问题讨论】:

    标签: function lua


    【解决方案1】:

    所有字符串共享同一个元表,将您的自定义函数添加到其__index 表中:

    function first_letter(str)
      return str:sub(1, 1)
    end
    
    local mt = getmetatable("")
    mt.__index["first_letter"] = first_letter
    
    local str = "stuff"
    print(str:first_letter())
    

    【讨论】:

    • 像文件这样的对象呢?他们也有单独的元表吗?顺便说一句,Lua 中所有类型的对象都有元表吗?
    猜你喜欢
    • 2015-02-05
    • 1970-01-01
    • 2019-12-30
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2013-05-08
    相关资源
    最近更新 更多