splitting lua strings into variables

989 Views Asked by At

I am pretty new to this, so I hope you can give me a hand.

I am programming lights, and what I like to do is take a variable from my lighting desk (a text string called "4 Mythos Stage") and split is into different variables.

to get the variables from the desk I use:

return function ()
local Layer1 = gma.user.getvar("Layer1") -- I placed "4 Mythos Stage" variable in Layer1
gma.feedback(Layer1) -- gives feedback 4 Mythos Stage
end

Now I would like to split the string into 3 new local variables named:

local number -- should produce 4
local fixturetype -- should produce Mythos
local location -- should produce Stage

i tried the following:

local number = string.match('Layer1', '%d+')
local fixturetype = string.match('Layer1', '%a+')
local location = string.match('Layer1', '%a+')

this didn't work, so can somebody please help me in the right direction. I would be really greatful.

with kind regards,

Martijn

2

There are 2 best solutions below

3
On

You can assign all three variables at the same time, because Lua has multiple returns and multiple assignment. Put parentheses around each of your patterns in order to return them as captures, and combine them into a single pattern with spaces between them:

local number, fixturetype, location = string.match(Layer1, '(%d+) (%a+) (%a+)')

In case you will be using multiple spaces or tabs between the items, this pattern would be better:

local number, fixturetype, location = string.match(Layer1, '(%d+)[ \t]+(%a+)[ \t]+(%a+)')

The reason why your attempt didn't work is because string.match('Layer1', '%d+') is searching inside 'Layer1' (a string) instead of Layer1 (a variable).

But even if you corrected that, you would get 'Mythos' every time you called string.match(Layer1, '%a+') (where Layer1 == '4 Mythos Stage'). string.match always starts from the beginning of the string, unless you supply an index in the third parameter: string.match(Layer1, '%a+', 9) --> 'Stage'.

0
On

A robust solution for this task is to split the string into three "words", a word being a sequence of non-whitespace characters:

local number, fixturetype, location = string.match(Layer1, '(%S+)%s+(%S+)%s+(%S+)')