0

I have some code, I want it to pick a random string from the list and convert it to a data type to be used in joypad.set() function. Here is my code:

Buttons = { A = true,
        B = true,
        Down = true}
while (true) do
   Random = math.random(3)
   NewButton = (Buttons[Random])
   joypad.set(1, (NewButton))
   emu.frameadvance();
end;

1 Answer 1

3

You don't state your problem, but from your code, it looks like you're not getting the values from the array you expect. You're getting a random number between 1 and 3, but A, B, and Down are not 1, 2, and 3. Buttons is an associative array (key-value pairs) the way you declare it, so if you want to use it this way, you will need to set up a second array with just the key names, and get a random index from that, like so:

ButtonKeys = { "A", "B", "Down" }
Random = math.random(3)
NewButton = (Buttons[ButtonKeys[Random]])

This creates a table with the values of A, B, and Down as index 1, 2, and 3, so you use the random number to get the value from the ButtonKeys array, then use that value as the index for the Buttons array.

Edit: I reread the question and went over my original answer and realized I was thinking about you declaring the table differently. The way you declare the table, A, B, and Down become properties of Buttons, which you can access by calling them directly like Buttons.A, Buttons.B, and Buttons.C, or by using brackets with a string name of the property you want to access. In your case, Buttons["A"], Buttons["B"], and Buttons["Down"].

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I reread the question and went over my answer, I was thinking A, B and Down were pre-declared variables, but that's not the case, it is creating the property A, B, and Down in ButtonKeys. I'll edit my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.