Nicht, dass ich würde es empfehlen, aber man konnte ziemlich nah an Pythons Syntax in Lua erhalten:
local A = require"A" -- see below for the implementation of module "A"
-- ...
local t = A[0] * 10
for i,v in ipairs(t) do
print(i, v)
end
Hier ist der Code für das Modul "A":
local M_meta = {}
local M = setmetatable({}, M_meta)
local function forbid_operation() -- to prevent mistakes
error("not a regular table, operation forbidden!")
end
local O_meta = {
__index = forbid_operation,
__newindex = forbid_operation,
__pairs = forbid_operation,
__ipairs = forbid_operation,
__mul = function(self, n)
if type(self) == "number" then
self, n = n, self -- swap values in case of e.g. `3 * A[0]`
end
local t, v = {}, self[ M_meta ]
for i = 1, n do
t[ i ] = v
end
return t
end,
__metatable = false,
}
local function index_or_call(self, v)
-- use M_table as a private key: no-one but this module
-- can access it, because it is local
return setmetatable({ [ M_meta ] = v }, O_meta)
end
M_meta.__index = index_or_call -- A[0] syntax
M_meta.__call = index_or_call -- A(0) syntax is also allowed
M_meta.__newindex = forbid_operation
M_meta.__pairs = forbid_operation
M_meta.__ipairs = forbid_operation
M_meta.__metatable = false
return M
Das Modul tatsächlich gibt eine Tabelle mit einem angepassten Metamethode __index
(und __call
) zurück. Wenn __index
oder __call
aufgerufen wird, wird eine andere Tabelle mit dem angegebenen Wert zurückgegeben, der in einem privaten Feld und einem __mul
metamethod dieses Mal gespeichert wird. Das Metamethod __mul
ruft den Wert aus dem privaten Feld ab und erstellt das Array der angeforderten Länge mit dem angegebenen Wert und gibt es zurück.
Nun, wenn Sie gewundene Lösungen nicht stört, gibt es auch dieses: local arr = load ('return {' .. ('0,'): rep (Größe) .. '}')() – tonypdmtr
Eine andere verschachtelte Lösung ist seit Lua 5.3 verfügbar: 'local arr = {table.unpack (setmetatable ({}, {__ index = function() return 0 end}), 1, size)}' –