0
votes

I am trying to create a Lua program using Sublime and Corona. I want to fetch a webpage, use a pattern to extract certain text from the page, and then save the extracted text into a table. I am using the network.request method provided by Corona

The problem: The extracted text is not saving into the global variable I created. Whenever I try to reference it or print it outside of the function it returns nil. Any ideas why this is happening?

I have attached a screen shot of my event.response output. This is what I want to be saved into my Lua table

Event.response Output

Here is my code:

local restaurants = {}
yelpString = ""

--this method tells the program what to do once the website is retrieved
local function networkListener( event )

    if ( event.isError ) then
        print( "Network error: ", event.response )
    else
         yelpString = event.response

        --loops through the website to find the pattern that extracts 
        restaurant names and prints it out
        for i in string.gmatch(yelpString, "<span >(.-)<") do
           table.insert(restaurants, i)
           print(i)
        end
    end
end

-- retrieves the website
network.request( "https://www.yelp.com/search?
cflt=restaurants&find_loc=Cleveland%2C+OH%2C+US", "GET", networkListener )
1
did you make sure networkListener is called? show how you print those texts outside the function... what are you trying to reference? restaurants or one of its fields? restaurants is not global btw...Piglet

1 Answers

0
votes

This sounds like a scoping problem. From the output you give, it looks like networkListener is being called, and you are successfully adding the text into the restaurants table. Moreover, since you define restaurants as a table, it should be a table when you reference it, not nil. So by deduction, the issue must be that you are trying to access the restaurants table from somewhere where it is not in scope.

If you declare restaurants as "local" in the top level of a file (i.e. not within a function or a block), it will be accessible to the whole file, but it won't be accessible to anything outside the file. So the table.insert(restaurants, i) in your code will work, but if you try to reference restaurants from somewhere outside the file, it will be nil. I'm guessing this is the cause of the problems that you are running into.

For more details on scope, have a look at the Programming in Lua book. The book is for Lua 5.0, but the scoping rules for local variables have not changed in later versions of Lua (as of this writing, the latest is Lua 5.3).