簡體   English   中英

如何創建自動處理表的 Lua 方法

[英]how to create Lua methods that work with tables automatically

In Lua, I see some methods such as the string and io class that allows you to call the method from the table automatically, without the need to instantiate an object for this, example:

以下代碼:

local tb = {"Hello", "World!"}

table.concat(tb)

可以這樣寫:

local tb = {"Hello", "World!"}

tb:concat()

我試圖創建一個可以做同樣事情的方法:

local tst = {}

function tst:test()
     print("test")
end

但以下代碼不起作用:

local tb = {"Hello", "World!"}

tb:test()

只有當我通知代碼tb = tst時:

local tb = tst

tb:test()

我的問題是,我有什么方法可以像第二個示例那樣自動創建與字符串或表一起使用的方法,而無需實例化 class? 比如,把我的表稱為表:MyMethod()

我不確定這是否回答了您最初的問題,但也許從評論中回答您的問題將有助於解釋事情。

以下代碼是如何使用某些方法實例化表的示例。

local function makeArray()
  local a = {}
  setmetatable(a, {__index = table})
  return a
end

setmetatable調用基本上使table庫中的所有函數都可以從新數組中訪問。 這很有用,因為除了pack之外的所有table函數都需要一個數組作為它們的第一個參數。

Vanilla Lua 對字符串做了類似的事情。 所有字符串都有{__index = string}作為它們的元表。

盡管代碼可以縮短,但 luther 是正確的:

function makeArray()
  return setmetatable({}, {__index = table})
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM