You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua多维数组如何实现类似numpy的索引访问方式?

Lua多维数组的元组式索引实现方案

原生Lua实现(无需扩展)

如果不想依赖第三方扩展,自己实现工具函数或封装数组类型即可解决问题。

方法1:通用工具函数取值

写一个遍历索引表的函数,逐层访问嵌套数组:

function get_element(arr, index)
    local current = arr
    for _, idx in ipairs(index) do
        current = current[idx]
        if not current then return nil end -- 处理索引越界/不存在的情况
    end
    return current
end

-- 配合原有数组使用
local index = {1,4,3,2}
print(get_element(a, index)) -- 输出 -1/6

方法2:封装支持表索引的数组类

通过元表__index重载索引操作,让自定义数组直接支持表索引,用法更贴近numpy:

local MultiArray = {}
MultiArray.__index = MultiArray

-- 创建多维数组:dimensions为维度表(如{5,4,3,2}),init_func为元素初始化函数(接收索引表参数)
function MultiArray.new(dimensions, init_func)
    local arr = {data = {}}
    -- 递归构建嵌套数组
    local function build(dims, path)
        if #dims == 0 then
            return init_func(path)
        end
        local t = {}
        local dim = table.remove(dims, 1)
        for i=1, dim do
            table.insert(path, i)
            t[i] = build(dims, path)
            table.remove(path)
        end
        return t
    end
    arr.data = build(dimensions, {})
    setmetatable(arr, MultiArray)
    return arr
end

-- 重载索引,支持表类型索引
function MultiArray:__index(key)
    if type(key) == "table" then
        local current = self.data
        for _, idx in ipairs(key) do
            current = current[idx]
            if not current then return nil end
        end
        return current
    else
        return MultiArray[key]
    end
end

-- 使用示例
local a = MultiArray.new({5,4,3,2}, function(path)
    local i,j,k,l = unpack(path)
    return (i - l)/(j + k - 1)
end)

local index = {1,4,3,2}
print(a[index]) -- 输出 -1/6

可用的Lua扩展

如果希望更贴近numpy的使用体验,可以考虑以下Lua库:

  • Torch:其torch.Tensor类型原生支持多维张量,允许用整数表直接索引,语法示例:tensor[{1,4,3,2}]。
  • Lunumpy:Lua与numpy绑定的库,可直接在Lua中使用numpy风格的数组对象,支持元组/表形式的索引访问。

内容的提问来源于stack exchange,提问作者Ted Black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 06:28:09