0

I'm looking for a Lua-equivalent of this Python code (if possible):

>>> ["prefix" + suffix for suffix in ["1","2","3"] ]
['prefix1', 'prefix2', 'prefix3']

This is the Lua code that I've currently got, I'm wondering whether there's a more compact way to code this:

function foo (prefix, suffices)
  local newList = {}
  for k,v in pairs(suffices) do
    table.insert(newList, prefix .. v)
  end
  return newList
end

a = foo( "prefix", {"1","2","3"} );
OLL
  • 655
  • 5
  • 20
  • Probably this is the most concise. Check here too: https://stackoverflow.com/questions/2050637/appending-the-same-string-to-a-list-of-strings-in-python – IoaTzimas Oct 05 '20 at 15:20
  • I'm confused. That link shows how to implement a one-liner in Python. I'm looking for a one-liner in Lua. – OLL Oct 05 '20 at 15:48
  • Sorry my mistake – IoaTzimas Oct 05 '20 at 15:56
  • @IoaTzimas, I thought that by "this" you meant the Lua code proposed by the author; and so far, i seems the most concise. Unless there's already a `map` function defined elsewhere. – Alexander Mashin Oct 05 '20 at 16:10

1 Answers1

0

There is no shorter way to do that.

function prepend_prefix(prefix, suffices)
  local newList = {}
  for _,v in ipairs(suffices) do
    newList[#newList+1] = string.format("%s%s", prefix, v)
  end
  return newList
end

And why would you keep these redundant prefix with each item? Why don't you wrap it with some "special" table (model) and expose a get method which prepend it for you?

Thing is, when you keep different strings (and it doesn't matter if they're almost identical) your memory usage will grow.

Adir Ratzon
  • 181
  • 3
  • 8