Search code examples
lua

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

  • 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.