user16999379
user16999379

Reputation:

Unable to print a function's parameter outside function even when returned

Contents is a table which is passed as a parameter for the function func. The issue is that I'm unable to print out any value from the table contents. For example here you can see I was trying to print the 2nd value in the table contents but I get this error 12: attempt to index global 'contents' (a nil value)

function func(contents)
  print(contents[1])
  return contents
end

func({"content1", "content2", "content3"})
print(contents[2])

Upvotes: 1

Views: 106

Answers (3)

Jason Goemaat
Jason Goemaat

Reputation: 29214

If your function will always use the global variable, create the global variable and don't take it as an argument to the function:

contents = {"content1", "content2", "content3"}

function func()
  print(contents[1])
  print(#contents)
  return contents
end

func()
print(contents[2])

If you do want to have a global variables, I'd suggest renaming your argument to avoid confusion. As this seems to just be a sample and your table seems to contain strings, I'll rename the argument 'strings' and show you can use the return value or the global variable (repl.it):

contents = {"content1", "content2", "content3"}

function func(strings)
  print(strings[1])
  print(#strings)
  return strings
end

local result = func(contents)
print(contents[2])
print(result[2])

Using global variables is frowned upon, you can make it local to your module and use it anywhere in your module by putting 'local' in front:

local contents = {"content1", "content2", "content3"}

Upvotes: 1

Piglet
Piglet

Reputation: 28950

how can I make contents global

Function parameter contents is local to func and is shadowing any variable named contents in a bigger scope.

A global variable name is just referring to a field in table _G. So in your function you could do

_G.contents = contents

But usually you avoid using global variables wherever possible.

As func returns contents simply do

print(func({"content1", "content2", "content3"})[2])

Upvotes: 0

ConnerWithAnE
ConnerWithAnE

Reputation: 1168

It is because you have the print(contents[2]) outside of the function. contents is local to the function only. According to the rest of the program contents does not exist thus it is throwing an error. There is no global variable contents and it is saying 12: which tells you the error is on line 12, which again, has the print(contents[2])

Upvotes: 0

Related Questions