灯光编程中Lua字符串分割为变量的实现求助
Splitting "4 Mythos Stage" into Local Variables in GrandMA2 Lua
Hey there! Since you're working with GrandMA2's Lua API, splitting that string into three local variables is straightforward. Here's how you can modify your code to get exactly what you need:
First, let's break down the task simply:
- Grab the string value from your
Layer1variable - Split it using spaces as the separator
- Assign each segment to its own named local variable
Modified Working Code
return function () local Layer1 = gma.user.getvar("Layer1") -- Retrieves "4 Mythos Stage" -- Split the string into three distinct parts local fixtureNumber, fixtureType, fixtureLocation = string.match(Layer1, "(%S+) (%S+) (%S+)") -- Test the variables to confirm they work (optional but helpful for debugging) gma.feedback("Fixture Number: " .. fixtureNumber) -- Outputs "Fixture Number: 4" gma.feedback("Fixture Type: " .. fixtureType) -- Outputs "Fixture Type: Mythos" gma.feedback("Fixture Location: " .. fixtureLocation) -- Outputs "Fixture Location: Stage" end
How This Works:
- The
string.matchfunction uses a pattern where%S+matches one or more non-space characters. The parentheses()around each%S+capture the matching segment into a separate variable. - Since your input string has exactly three space-separated parts, this pattern perfectly maps each part to the variables you define (feel free to rename
fixtureNumber,fixtureType, etc., to whatever fits your workflow best!).
Robust Alternative (For Inconsistent Spacing):
If you ever need to handle strings with extra or inconsistent spaces, this method is more reliable. It collects all non-space segments into a table first, then assigns them to variables:
return function () local Layer1 = gma.user.getvar("Layer1") local stringParts = {} -- Iterate through all non-space segments and add to the table for segment in string.gmatch(Layer1, "%S+") do table.insert(stringParts, segment) end -- Assign table entries to local variables local fixtureNumber, fixtureType, fixtureLocation = stringParts[1], stringParts[2], stringParts[3] gma.feedback("Split Result: " .. fixtureNumber .. ", " .. fixtureType .. ", " .. fixtureLocation) end
This second approach works even if there are multiple spaces between parts, but for your specific use case, the first method is simpler and more direct.
内容的提问来源于stack exchange,提问作者Martijn van Dam
相关产品推荐
相关产品推荐

