How to create a new vim command in lua?

I am writing a pure lua init, so I need to convert the command:

command! BufOnly silent! call Preserve("exec '%bd|e#|bd#'")

By the way, the explanation about the above command is here:

Would this work?
If Preserve has a 100% chance of being defined:

vim.api.nvim_create_user_command('BufOnly',function()
  pcall(vim.fn.Preserve("exec '%bd|e#|bd#'"))
end,{})

If Preserve may not be defined:

vim.api.nvim_create_user_command('BufOnly',function()
  pcall(function()
    vim.fn.Preserve("exec '%bd|e#|bd#'")
  end)
end,{})
3 Likes