Not that I would recommend it, but you could get pretty close to Python's syntax in Lua:
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
Here is the code for module "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
The module actually returns a table with a customized __index (and __call) metamethod. When __index or __call is invoked, another table is returned with the given value stored in a private field and a __mul metamethod this time. The __mul metamethod retrieves the value from the private field and creates the array of the requested length with the given value, and returns it.
local arr = {table.unpack(setmetatable({},{__index=function()return 0 end}),1,size)}