while true do
("Tween"..TweenPlayingValue.Value):Play()
MotorOn.Changed:Connect(MotorOnOffValueTrigger)
("Tween"..TweenPlayingValue.Value).Completed:Wait()
end
How do you combine 2 strings to find a variable. Here there is a variable called Tween1
I want the while true do to play Tween…“The value of the variable”, which could have a value of 1-8. Depending on the value, it will play tween1-8. How do you do this, as im getting a error on the script saying this
Lua doesn’t support that kind of dynamic variable lookup directly. Instead, concatenating a string like this will just produce a string value, not a reference to an actual variable.
("Tween"..TweenPlayingValue.Value) creates a string but doesn’t translate into a variable reference, so Lua won’t recognise it as Tween1, Tween2, etc. Additionally, Lua throws an error about ambiguous syntax because it tries to interpret the parentheses as part of a function call.
There are workarounds but they are heavily dependent on what your environment is like.
Not quite, you don’t have to manually write out each condition. There’s a better way to handle it without repeating code, using either the _G global table or a table of tweens.
Solution with _G (for Global Variables)
If Tween1, Tween2, etc., are global variables (defined without local), you can use Lua’s _G table to access them dynamically based on TweenPlayingValue.Value:
while true do
-- build the name dynamically
local tweenVariableName = "Tween" .. TweenPlayingValue.Value
-- access the tween via the _G table
local tweenToPlay = _G[tweenVariableName]
if tweenToPlay then
tweenToPlay:Play()
MotorOn.Changed:Connect(MotorOnOffValueTrigger)
tweenToPlay.Completed:Wait()
else
print("Invalid tween variable: " .. tweenVariableName)
end
end
But this approach only works if each tween variable (Tween1, Tween2, etc.) are global.
Solution with a Table (for Local Variables)
A safer approach is to store your tweens in a table, which avoids global variables. Here’s how:
Define a table with all the tweens.
Access the tween directly by index.
-- define all tweens in a table
local tweens = {Tween1, Tween2, Tween3, Tween4, Tween5, Tween6, Tween7, Tween8}
while true do
local tweenToPlay = tweens[TweenPlayingValue.Value] -- access by index, so if the tweenplayingvalue is 3 it will catch the 3rd index in the table, which is tween3
if tweenToPlay then
tweenToPlay:Play()
MotorOn.Changed:Connect(MotorOnOffValueTrigger)
tweenToPlay.Completed:Wait()
else
print("Invalid tween value: " .. TweenPlayingValue.Value)
end
end
Please try both solutions and tell me if either work, along with any error messages or concerns.
If these solutions fail, please provide me with more of a script preview so I can tell what I’m working with.