Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Selecting a table by name.

edited August 2014 in Questions Posts: 24

I have some .lua files that are my decks of cards. Each .lua file represents a deck and is really just a simple array like deck1 = {card1,card2,card3}

I have a picker that allows a player to select a deck like so: selected_deck = images[counter] the result of that selection would be the deck I want. In this case deck1 is the value of selected_deck

Here is my problem :) I need to call the lua table that corresponds with the value selected_deck, but I can't use the selected_deck value although it has the same name of my table(deck1), it does not actually reference the table. It is a variable out on its own.

How do I select deck1 table at this stage so that I can read the cards out of it? Thanks.



  • I should add that normally I would call require on the lua file by the images[counter] value like require images[counter].."lua" and load it as needed. I can't do this in Codea I don't think.

  • IgnatzIgnatz Mod
    Posts: 5,396

    @swiftjuan - you can do it at least two ways

    1- set up a deck class, then you can have a table of decks

    or (especially if you are unfamiliar with classes)

    2- put your decks in their own table, eg

    --or if you've already created your decks in their own variables
    decks["deck 1"]=deck1
    decks["deck 2"]=deck2
    --or perhaps
           deck2={card1,card2,card3}, etc

    Then it is quite easy to refer to the deck you want by looking it up in decks.

  • Posts: 509

    If your tables are global, you can access them via the _G table: _G[var] is equivalent to var. So you could do _G["deck" .. choice].

    An alternative which is closer to what you describe in your second post is to have the decks in a second project. Then you can read the file using readProjectTab (I think) without it being automatically loaded. You'd have to use loadstring to process it, though. You could be a bit fancy and have them in the same project but as comment files: stick --[[ at start and --]] at end (maybe --[==[ and ]==]-- if you have block comments already in the file). Then after reading it in via readProjectTab, strip off the comment lines before passing it to loadstring.

  • Thanks for the feedback. LoopSpace, I came up with the same idea. Here is what I did:

    added tab called "animals" which is the name of the deck and added the string with all my animals like so. --,duck,pig,cat,dog,lion

    In main.lua. I turn the string into a table without the first element--. Now I am free to read out the deck.

    The great thing is that every time I add a new deck, I just create a lua file for the deck, and add the deck name to another tab called packs. I do not have to alter main.lua at all to add decks.

    I hoping to provider additional decks for a an in app purchase, so this was essential.

Sign In or Register to comment.