lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 2017-06-25 00:58, Dibyendu Majumdar wrote:
I wonder if the language would be more powerful if it had a distinct
array type.

I think not, I don't see anything useful that this would add.  Tables
work just fine as arrays (and they're optimized for that use.)

Just having a different type doesn't improve anything.  (If type errors
count as an improvement, using a metatable as a type tag & checking that
already works – that doesn't need a new type.)  What actually adds value
is library functions and built-in features you no longer have to worry
about.  But the library functions can just as well be written to operate
on (array-like) tables, so there's no need for a new type from that
aspect.  Which leaves built-in features as the last possible reason.  If
I go through the list of array-specific functionality that I might want
– bounds checks (use __[new]index metamethod), multidimensional indexing
or range selection or ... (use a/several method(s)), ... – I don't see
anything that's not already doable in a reasonably efficient & usable
way.  Really funky features (arbitrary transposition/index reordering,
slicing, ...) are complex either way.  I don't see any obvious advantage
to implementing them on a "real" array type vs. tables.

Coming from a different perspective:  How would you implement the array
type in C?  You have pointers, structs, and arrays / memory regions as
primitives to build upon.  No matter how you implement it, you can
essentially do the same thing using tables as the sole primitive.
Structs are obvious, as are arrays.  Pointers to (the start of) things
are also obvious: just use the reference.  Pointers _into_ things may
seem hard at first, but you can view tables as non-overlapping memory
segments or mappings of unspecified / arbitrary size, which makes the
solution obvious:  Use pairs of (base pointer, offset) or { base =
some_table, offset = int }.  (Which is conveniently a thing that can be
pointed at, so pointers to pointers to … are also easy.  And if you
don't need that, you can usually fold this (base,offset) pair into the
parent structure to avoid allocating tons of tiny "pointer tables".)

So any array type implementation that you write in C can be written in /
translated into Lua as well.  The translation does not involve any
costly emulation of "missing features", so it shouldn't be prohibitively
slow or huge.  Which means you can just build the array type and all its
functionality on top of tables and don't need a separate primitive type.

-- nobody