Error accessing a module function - function

I have a problem with basic module usage in Lua. I have one file "helloworld.lua" and a second file "main.lua". I would like to call a function from the first file inside the second file. But I am getting an error:
attempt to call field 'printText' (a nil value)
My actual code is below. Can someone tell me where the problem is?
helloworld.lua
local module = {}
function module.printText()
print("Hello world")
end
return module
main.lua
hello = require("helloworld")
hello.printText()

As mentioned in the comments, this is the right way to do it. This could be a problem if there is a conflicting helloworld module, or if you have a running lua state and are modifying the files without starting a new one.
require will only load the module passed with a string once. Check package.loaded["helloworld"]. You can set this to nil so that require will load the file again:
package.loaded["helloworld"] = nil
hello = require("helloworld") -- will load it for sure

Related

attempt to index global 'INV' (a nil value) (line:23)

print("cl_inv wurde geladen!")
concommand.Add("inv_model", function(ply)
local wep = ply:GetActiveWeapon()
if not IsValid(wep) then return end
print(wep:GetWeaponWorldModel())
end)
net.Receive("inv_init", function()
LocalPlayer().inv = {}
end)
net.Receive("inv_give", function()
local classname = net.ReadString()
table.insert(LocalPlayer().inv, classname)
end)
function INV.Open()
local ply = LocalPlayer()
local plyinv = ply.inv
if not ply.inv then return end
local scrw, scrh = ScrW(),ScrH()
INV.Menu = vgui.Create("DFrame")
local inv = INV.Menu
inv:SetSize(scrw * .4, scrh * .6)
inv:Center()
inv:SetTitle("")
inv:MakePopup()
inv.Paint = function(me,w,h)
surface.SetDrawColor(0,0,0,200)
surface.DrawRect(0,0,w,h)
end
local scroll = inv:Add("DScrollPanel")
scroll:Dock(FILL)
scroll.panels = {}
for k,v in pairs(plyinv) do
local itemPanel = scroll:Add("DPanel")
itemPanel:Dock(TOP)
scroll.panels[itemPanel] = true
end
end
hook.Add( "OnPlayerChat", "InvOpen", function( ply, strText, bTeam, bDead )
if ( ply != LocalPlayer() ) then return end
if string.lower(strText) != "!inv" then return end
INV.Open()
end )
I already searched the whole internet for a solution, i did found something but it didnt really helped me so what im expecting is that someone may be so nice and can help me solve my problem. In line 23 is the error :attempt to index global 'INV' (a nil value) (line:23)
As I can see, you're using the Garry's Mod Lua API. Although this API adds some features to the basic Lua language (e.g. ! operator for negation, C-style comments //), you still need to use the Lua language properly.
What the error says, is that you're trying to access to a table that isn't defined in the current scope of your program.
I can bet your addon defined some global table to interoperate between files and other addons installed on your machine.
As I don't have that much information on the way you're loading your file, here are multiple guesses on possible solutions:
For a file located inside an autorun folder
If the snippet you gave is under an autorun folder, the issue may be that the INV table does not yet exist when you load your file. To correct that, you can use the GLua Timer's Library.
Here is a simple snippet:
Timer.Simple(0.2, function()
-- put your code here
end
Timer.Simple takes two parameters: first one is a delay, in seconds and the other one is a callback function, executed once the delay has ended !
If you're doing something that requires the server to have loaded some other addons before actually running your script, this might be helpfull.
Accessing Global variables of your environment
As you did not gave that many informations about your problem I have to continue to guess what you're trying to do. An other source of problem is maybe that the INV table simply doesn't exist.
How to get all defined global tables in Lua ?
In Lua, there is the _G table that contains all the data of your current environnement. For more in-depth information, please see the official Lua documentation.
To know if your table does in fact exist in your environment, you can run this snippet on your Lua server:
local function doesINVExist()
for name in pairs(_G) do
if (name == "INV") then return true end
end
return false
end
And then you can simply run it using:
print(doesINVExist())
What to do if the table doesn't exist
If INV isn't present in your environment, then it may be because your Garry's Mod server did not loaded any file that defines such a table. Then what you can do is checking the addon that should dclare that table to see if there are any errors that might make it a nil value.
I hope this can help. Of course my answer could've been much more detailed if I had more information. But as I can't write comments (my rating isn't high enough), here is all I can do for you !
Have a great day,
Pedro.

Scope of variable in golang

I am trying to run one function in golang but I am getting some errors. Can anyone please help.
func exportVal(name string, value string){
var ops = isWindows()
if ops == true{
set name=value
fmt.Printf("name=")
}else{
export name=value
fmt.Printf("name=")
}
}
But I am getting below error.
D:\Go>go run octa.go
# command-line-arguments
.\octa.go:42:10: syntax error: unexpected name at end of statement
.\octa.go:46:13: syntax error: unexpected name at end of statement
set and export are not Go keywords. Maybe you're thinking of shell? It looks like you're trying to set and export environment variables.
You cannot export environment variables from one process to another. You can only change your own process's environment. Child processes will inherit the parent's environment, but you can't go the other way. You can only do it in a shell program because that "program" is really a set of commands to the shell itself, and only then when using source something.sh. sh something.sh, in contrast, is run in a new shell process.
If you want to "export" data from a non-shell program, you'll have to print out the data in some format, JSON is a good choice, and have that be read by the other process.
Go doesn't support the export keyword.
Are you trying to create a variable with global scope?
var foo string
func SetFoo(to string) {
foo = to
}
Or are you trying to set an environment variable? In which case, use os.Setenv(key, value).

Using require on a .json file will return an empty array if file is being required by another function at the same time

I don't have much experience with node but I've run into a pitfall when running code that handles I/O (a simplification of my code):
I have data.json which contains ['foo','bar'] with many functions that read and parse this file like so:
// foo.js
module.exports = function() {
// do stuff
var data = require("path/to/data.json");
return data;
};
// bar.js
module.exports = function() {
// do stuff
var data = require("path/to/data.json");
return data;
};
However when I call them:
// main.js
var foo = require('foo');
var bar = require('bar');
console.log(foo()); // gives ['foo','bar']
console.log(bar()); // gives []
I suspect while foo is reading data.json, it "locks" the file then preventing bar from reading it, but I'm not sure why bar still returns an empty array instead of undefined.
Using require to read a json file was a bad idea as I have them littered throughout my entire codebase. Is there an easy fix for something like this? What would be the preferred method of reading json files knowing that at any given moment that file might be accessed by another function?
As we know, require() will always cache the content of the loaded module (or file, in this case). The next time require() is called again, it will restore it from the cache instead of reading it again.
In your case, you was reading the file once for each foo.js and bar.js. Here, foo had changed a value from the JSON, and because it’s content was cached by require(), the changed value was loaded into bar, in which I was expecting it to be the original value. But, since foo already read it till end, you are at EOF. So, bar returns empty array [there is nothing to read, but file is valid].
SOLUTION:
Stick with fs module when reading JSON files.

List Lua functions in a file

How can I list all the functions included in a Lua source file?
For example, I have fn.lua which contains
function test1()
print("Test 1")
end
function test2()
print("Test 2")
end
And I wish to be able to display those function names (test1, test2) from another Lua script.
The only way I can figure at the moment is to include the file using require, then list the functions in _G - but that will include all the standard Lua functions as well.
Of course I could just parse the file manually using the string search functions, but that doesn't seem very Lua to me!
This will eventually form part of a process that allows the developer to write functions in Lua, and the operator to select which of those functions are called from a list in Excel (yuk!).
If you put them all in a "module" (which you should probably do, anyway):
mymodule = { }
function mymodule.test1()
print("Test 1")
end
function module.test2()
print("Test 2")
end
return mymodule
It becomes trivial:
mymodule = require"mymodule"
for fname,obj in pairs(mymodule) do
if type(obj) == "function" then
print(fname)
end
end
If you absolutely have to keep them in raw form, you'd have to load them in a different way to separate your global environment, and then iterate over it in a similar way (over the inner env's cleaned _G, perhaps).
I see three ways:
Save the names in _G before loading your script and compare to the names left in _G after loading it. I've seen some code for this, either in the Lua mailing list or in the wiki, but I can't find a link right now.
Report the globals used in a function by parsing luac listings, as in http://lua-users.org/lists/lua-l/2012-12/msg00397.html.
Use my bytecode inspector lbci from within Lua, which contains an example that reports globals.
If you want to do this, it's better to define the function is a package, as described in Programming in Lua book:
functions = {}
function functions.test1() print('foo') end
function functions.test2() print('bar') end
return functions
Then you can simply iterate your table functions.

Accessing the Body of a Function with Lua

I'm going back to the basics here but in Lua, you can define a table like so:
myTable = {}
myTable [1] = 12
Printing the table reference itself brings back a pointer to it. To access its elements you need to specify an index (i.e. exactly like you would an array)
print(myTable ) --prints pointer
print(myTable[1]) --prints 12
Now functions are a different story. You can define and print a function like so:
myFunc = function() local x = 14 end --Defined function
print(myFunc) --Printed pointer to function
Is there a way to access the body of a defined function. I am trying to put together a small code visualizer and would like to 'seed' a given function with special functions/variables to allow a visualizer to 'hook' itself into the code, I would need to be able to redefine the function either from a variable or a string.
There is no way to get access to body source code of given function in plain Lua. Source code is thrown away after compilation to byte-code.
Note BTW that function may be defined in run-time with loadstring-like facility.
Partial solutions are possible — depending on what you actually want to achieve.
You may get source code position from the debug library — if debug library is enabled and debug symbols are not stripped from the bytecode. After that you may load actual source file and extract code from there.
You may decorate functions you're interested in manually with required metadata. Note that functions in Lua are valid table keys, so you may create a function-to-metadata table. You would want to make this table weak-keyed, so it would not prevent functions from being collected by GC.
If you would need a solution for analyzing Lua code, take a look at Metalua.
Check out Lua Introspective Facilities in the debugging library.
The main introspective function in the
debug library is the debug.getinfo
function. Its first parameter may be a
function or a stack level. When you
call debug.getinfo(foo) for some
function foo, you get a table with
some data about that function. The
table may have the following fields:
The field you would want is func I think.
Using the debug library is your only bet. Using that, you can get either the string (if the function is defined in a chunk that was loaded with 'loadstring') or the name of the file in which the function was defined; together with the line-numbers at which the function definition starts and ends. See the documentation.
Here at my current job we have patched Lua so that it even gives you the column numbers for the start and end of the function, so you can get the function source using that. The patch is not very difficult to reproduce, but I don't think I'll be allowed to post it here :-(
You could accomplish this by creating an environment for each function (see setfenv) and using global (versus local) variables. Variables created in the function would then appear in the environment table after the function is executed.
env = {}
myFunc = function() x = 14 end
setfenv(myFunc, env)
myFunc()
print(myFunc) -- prints pointer
print(env.x) -- prints 14
Alternatively, you could make use of the Debug Library:
> myFunc = function() local x = 14 ; debug.debug() end
> myFunc()
> lua_debug> _, x = debug.getlocal(3, 1)
> lua_debug> print(x) -- prints 14
It would probably be more useful to you to retrieve the local variables with a hook function instead of explicitly entering debug mode (i.e. adding the debug.debug() call)
There is also a Debug Interface in the Lua C API.