Referencing variable in a table from another doc

3 replies [Last post]
sirnemo
User offline. Last seen 1 week 1 hour ago. Offline
Joined: 29 Oct 2012

This is a fairly simple concept that I just can't get the right syntax for, so I'd like some help!

One doc says...

1
2
3
4
5
6
7
8
9
10
--doc1.lua
local scene = {
  objects = {
    { -- The Player
      name = "player",
      img = "art/player.png",
      start_x = -170,
      start_y = -4720,
      },
    },

Is it possible to reference "player" by name? How?

So far, I have, in a separate lua document,

1
2
3
4
5
6
7
8
--doc2.lua
local function enemy(self, event)
        local scene = require("doc1")
        -- ??? Something goes here.
        if(self.y <= player.y) then
        print("SUCCESS")
        end
end

How do I make "success" happen? :) Thanks.

Replies

richard9
User offline. Last seen 38 min 50 sec ago. Offline
Joined: 28 Feb 2011

You have to return things you want to retrieve from other files. This is how storyboard works, because you use a bunch of storyboard.* functions to create each scene, and then type return scene at the end to pass the data on.

Similarly I can make a lua file myself like this;

1
2
3
4
--cool.lua
local rabbits = {2,3,4}
 
return rabbits

If I require in cool.lua elsewhere,

1
2
local cool = require("cool")
print( cool[1] ) -- 2

The trick with your code is that just because you're returning something doesn't mean it will attach everything in it:

1
2
3
local rabbit = {}
rabbit.name = "robert" -- this is part of rabbit, so it goes with it
blob = "derek" -- this is not a part of rabbit, so it doesn't go with it

So you can type return objects in doc1, but that won't give you the scene table, which means in doc2, scene == objects.

sirnemo
User offline. Last seen 1 week 1 hour ago. Offline
Joined: 29 Oct 2012

Thank you, that helped a lot. I'm going to have to restructure things a bit. Nice moogle avatar, btw. :)

develephant
User offline. Last seen 6 days 19 hours ago. Offline
Joined: 6 Dec 2012

I'd be cautious about using "scene" as a variable if you plan on using Storyboard, as it's used a lot in the docs, and you may inadvertently overwrite it.

To gain access to you data easier, I would assign it to a "player" key:

In doc1.lua:

1
2
3
4
5
6
7
local sceneData = {
  objects = {
    player = { name = "player", img = "art/player.png", start_x = -170, start_y = -4720 }
  }
}
 
return sceneData

In doc2.lua

1
2
3
4
5
6
7
local function enemy(self, event)
   local sceneData = require("doc1")
   -- ??? Something goes here.
  if(self.y <= sceneData.objects.player.start_y) then
    print("SUCCESS")
  end
end

Just a suggestion. Cheers.

Viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.