'How to prepend an item to Lua array?
As title. I'm working with a neovim config, and the content of this array will be concatenated into a command to execute:
cmd = { 'mono', omnisharp_bin, '--languageserver', '--hostPID', tostring(vim.fn.getpid()) }
like this one but imagine that the 'mono' has not been prepended.
Solution 1:[1]
You can use table.insert:
cmd = { omnisharp_bin, '--languageserver', '--hostPID', tostring(vim.fn.getpid()) }
table.insert(cmd, 1, 'mono')
-- cmd is now what you want
You can use either table.insert(mytable, position, value) to insert value at position position and shift all the values after that over, or use table.insert(table, value) to insert a value at the end of the array part.
Solution 2:[2]
To answer it myself (since I was also diving into this question before I saw these answers. thanks):
cmd = { 'mono', unpack(cmd) }
I think this one might be slow, but it's simple so it's elegant.
Solution 3:[3]
And imagine cmd is an object and can handle all by itself...
cmd = setmetatable({ omnisharp_bin,
'--languageserver',
'--hostPID',
tostring(vim.fn.getpid()) },
{__index = table}) -- This adds all table functions to cmd
cmd:insert(1, 'mono')
print(cmd:concat(' ',1 , #cmd))
-- As LMD wrote in comment, 1 and #cmd not really needed here
-- It shows concat()' default behaviour and could inspire
-- That you can pick with concat() a range of numbered keys
-- Or only one with: cmd:concat('', 1, 1)
-- Especially the zero and also negativ numbers
Important:
cmd.insert() means: Use from cmd
( like table.insert(cmd, 1, 'mono') )cmd:insert() means: Use with cmd
( Without cmd as first argument )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jasmijn |
| Solution 2 | VimNing |
| Solution 3 |
