Lua 5.3字符串库中的所有函数名称是什么?

这是一个我用来注册库名称的函数名注册闭包:

对象池(Pool):

function FooBarPool()
  local Names = {}
  local self = {}
    function self:Register(fFoo,sName)
      if(fFoo) then
        Names[fFoo] = sName
      end
    end
    function self:GetName(fFoo)
      return Names[fFoo] or "N/A"
    end
  return self
end

创建一个 Pool 对象:

local Pool = FooBarPool()

注册已知的库函数:

Pool:Register(string.sub,"string.sub")
Pool:Register(string.gsub,"string.gsub")
Pool:Register(string.match,"string.match")
Pool:Register(string.gmatch,"string.gmatch")
Pool:Register(string.find,"string.find")
Pool:Register(string.gfind,"string.gfind")
Pool:Register(string.format,"string.format")
Pool:Register(string.byte,"string.byte")
Pool:Register(string.char,"string.char")
Pool:Register(string.len,"string.len")
Pool:Register(string.lower,"string.lower")
Pool:Register(string.upper,"string.upper")
Pool:Register(string.rep,"string.rep")
Pool:Register(string.reverse,"string.reverse")

for k,v in pairs(string) do
  print(tostring(v) .. " : "..Pool:GetName(v))
end
点赞
用户107090
用户107090

如果你在最后一个循环中添加了print(k,v),你会发现你缺少了string.dump

函数string.gfind不是标准的。它出现在Lua 5.0中,但在Lua 5.1中被重命名为string.gmatch

你可以用下面的代码获取string库中所有的名称:

for k in pairs(string) do
    print(k)
end

或参考手册

2015-02-03 10:19:19
用户3052908
用户3052908

为什么不将字符串库中的字符串函数列在一个数组中,然后使用pairs函数进行迭代,就像这样:

strings = {"string.sub", "string.gsub", ..., "string.reverse"};
for _k,v in pairs(strings) do print(v) end;

我发现这比以上给出的答案更容易实现。 顺便问一下,有没有更好的方法来解包所有的字符串库字符串函数,而不必将它们列在一个表中?

2015-04-01 14:08:15