gustavo-hms / luar

Script Kakoune using Lua
GNU Lesser General Public License v3.0
45 stars 3 forks source link

Confusion when passing %val{selections} as an argument #15

Closed sucrecacao closed 3 years ago

sucrecacao commented 3 years ago

When writting:

    lua %val{selections} %val{main_reg_hash} %{
        sels = arg[1]
        main_index = arg[2]

I would expect sels to be a table with selections, instead I get the value of my first selection because it is arg holding the table instead of arg[1]. Then, how can I get the value of my second argument?

gustavo-hms commented 3 years ago

This is due to the way Kakoune handles expansions: %val{selections} is replaced by a quoted list of the selections' contents. So, for instance, if you have two selections containing “uma frase” and “outra frase”, %val{selections} will be replaced by 'uma frase' 'outra frase'. These are then passed as command line arguments to the lua interpreter and end up filling the arg table in your code. That's why each selection is in a different position of the arg table.

To do what you want, I propose 2 different solutions:

Quote the first expansion

You can quote the first expansion:

lua "%val{selections}" %val{main_reg_hash} %{ ... }

Double quotes are needed here because Kakoune doesn't process expansions inside single quoted strings.

Now, all your selections are in arg[1], but as a single giant string. You then need to use string.gmatch (see https://www.lua.org/manual/5.4/manual.html#6.4) to iterate over each one.

Extract the last element

You can just pretend the value of %val{main_reg_hash} isn't in the last position:

lua %val{selections} %val{main_reg_hash} %{
    local main_reg_hash = arg[#arg] -- the `#` operator gets the lengths of the table

    for i = 1, #arg-1 do
        local selection = arg[i]
        ....
    end
}

Or, even better:

lua %val{selections} %val{main_reg_hash} %{
    local main_reg_hash = table.remove(arg) -- removes the last element by default

    for i, selection in ipairs(arg) do -- now, `arg` contains only the selections
        ....
    end
}

By the way, what does main_reg_hash contain? I couldn't find it in doc expansions...

sucrecacao commented 3 years ago

Thanks, the second solution looks cleaner for me, it worked ! :)

main_reg_hash gives you the index of the main selection. %val{selections} Is sorted by line number, so you have no idea which one the the main seleciton ( in opposition of %val{selections_desc} where the main selection is in the first place ). main_reg_hash could be called main_selection_index