【问题标题】:What does # mean in Lua?# 在 Lua 中是什么意思?
【发布时间】:2013-08-01 05:29:40
【问题描述】:

我在 Lua 中看到很多变量前面添加了哈希字符“#”。

它有什么作用?

示例

-- sort AIs in currentlevel
table.sort(level.ais, function(a,b) return a.y < b.y end)
local curAIIndex = 1
local maxAIIndex = #level.ais
for i = 1,#currentLevel+maxAIIndex do
    if level.ais[curAIIndex].y+sprites.monster:getHeight() < currentLevel[i].lowerY then
        table.insert(currentLevel, i, level.ais[curAIIndex])
        curAIIndex = curAIIndex + 1
        if curAIIndex > maxAIIndex then
            break
        end
    end
end

抱歉,如果已经有人问过这个问题,我在互联网上搜索了很多,但似乎没有找到答案。提前致谢!

【问题讨论】:

    标签: lua


    【解决方案1】:

    那是length operator

    长度运算符由一元运算符# 表示。字符串的长度是它的字节数(即每个字符为一个字节时字符串长度的通常含义)。

    表 t 的长度被定义为任意整数索引 n,使得 t[n] 不为 nil 且 t[n+1] 为 nil;此外,如果 t[1] 为 nil,则 n 可以为零。对于从 1 到给定 n 的非 nil 值的常规数组,它的长度正好是 n,它的最后一个值的索引。如果数组有“洞”(即,其他非 nil 值之间的 nil 值),那么 #t 可以是直接在 nil 值之前的任何索引(也就是说,它可以将任何这样的 nil 值视为结束的数组)。

    【讨论】:

    • 有什么理由会出现语法错误unexpected symbol near #'`?这是别人的代码,似乎没有其他人有问题......
    【解决方案2】:

    # 是 lua 长度运算符,适用于字符串或表 数组

    例子:

    print(#"abcdef")  -- Prints 6
    print(#{"a", "b", "c", 88})  -- Prints 4
    
    -- Counting table elements is not suppoerted:
    print(#{["a"]=1, ["b"]=9}) -- # Prints 0
    

    【讨论】:

      【解决方案3】:

      #最常用于获取表格的范围。例如:

      local users = {"Grace", "Peter", "Alice"}
      local num_users = #users
      
      print("There is a total of ".. num_users)
      

      输出: 3

      【讨论】:

      • 或者获取字符串的长度:print(#_VERSION) -- Result is: 7
      猜你喜欢
      • 2016-04-15
      • 2015-01-22
      • 2019-01-03
      • 1970-01-01
      • 2011-08-12
      • 2017-06-11
      • 2018-03-05
      • 2023-03-27
      • 2021-03-01
      相关资源
      最近更新 更多