I am new to lua,i just don't know why,does it related to environment or the libarary?it drive me crazy, i being search the answer for hours.
function gradient()
local maxStep = 10;
local starColor="41B0F7";
local endColor ="1622DF";
local sb = tonubmer(string.sub(starColor,1,2),16);
return sb;
end
print(gradient());
There are two things going on here:
Lua standard library functions like tonumber are global variables.
If you try to access a global variable that does not exist (in this case, tonu*bm*er) you get nil ny default.
I recommend using a linting tool like LuaInspect to detect these typos before they bite you.
Related
I want to add some methods or properties to a lua object witch metadata was created by C API. I can't add property in normal way, for example:
local foo = libc.new()
foo.bar = "hello"
it say:
Failed to run script: attempt to index a libc_meta value (local 'foo')
So I think maybe need to modify metatable, so I change my code:
local foo = libc.new()
local mt = getmetatable(foo)
foo[bar] = "hello"
setmetable(foo, mt)
Unfortunately, it still doesn't work.
Failed to run script: bad argument #1 to 'setmetatable' (table expected, got libc_meta)
So how can I add methods or properties to this 'foo'?
BTW, c code is here:
static int libc_new(lua_State *L) {
...
lua_lib_space *libc = lua_newuserdata(L, sizeof(*libc));
libc->L = L;
libc->cb_enter = cb_enter;
libc->cb_leave = cb_leave;
luaL_getmetatable(L, "libc_meta");
lua_setmetatable(L, -2);
lib_space *lib = lib_new(enter, leave, libc);
libc->space = lib;
return 1;
}
Userdata is meant to be created by C, manipulated by C code, and for only the purposes that C code intends. Lua can talk to it, but only in the ways that C allows it to. As such, while userdata can have a metatable (and those metamethods are the only way Lua can "directly" interact with the userdata), only C functions (and the debug library, but that's cheating) can directly manipulate that metatable. Lua is an embedded language, and C has primacy; if some C library wants to shut you out, it can.
What you can do is take the userdata and stick it in a table of your own, then give that table a metatable. In your __index metamethod, if you have an override or new method for a particular key, then you forward the accesses to that. Otherwise, it will just access the stored userdata.
However, if what you get in the userdata is a function, then you may have a problem. See, most userdata functions take the userdata as a parameter; indeed, most are meant to be called via "ud:func_name(params). But if thatud` is actually the table wrapper, then the first parameter passed to the function will be the wrapper, not the userdata itself.
That poses a problem. When the thing you get from the userdata is a function, you would need to return a wrapper for that function which goes through the parameters and converts any references to the wrapper table into the actual userdata.
In ROBLOX Lua, I'm writing a game that involves users creating and running Lua scripts. Obviously, I need to prevent the use of certain services and functions, such as the Kick function on the Player class, or anything related to DataStore or TeleportService.
So far, I've been successful at making a sandboxed environment by using setfenv to set a function's environment to a metatable, which is attached to a "sandbox" table. On __index, if nothing is found in the sandbox table, it looks in the real environment like it normally would. This allows me to put fake functions in the sandbox table that will be used instead of their real counterparts.
However, let's say I sandboxed the ClearAllChildren function. Players could easily escape the sandbox by doing this:
someObject.Parent.someObject:ClearAllChildren()
This is because getting an instance's Parent gives them the real version as opposed to the sandboxed version. This flaw can be pulled off many other ways, too.
So I made an object wrapper. Calling wrap(obj) on an instance returns a fake version created with newproxy(true). The __index of its metatable makes sure any child of the object (or instance property such as Parent) will return a wrapped version.
My issue is likely with the way I have my wrapper set up. Attempting to call any method on an object inside the sandbox, like this:
x = someObject:GetChildren()
Results in the following error:
Expected ':' not '.' calling member function GetChildren
Here's the full code for my sandbox currently:
local _ENV = getfenv(); -- main environment
-- custom object wrapper
function wrap(obj)
if pcall(function() return obj.IsA end) then -- hacky way to make sure it's real
local realObj = obj;
local fakeObj = newproxy(true);
local meta = getmetatable(fakeObj);
meta['__index'] = function(_, key)
-- TODO: logic here to sandbox wrapped objects
return wrap(realObj[key]) -- this is likely the source of method problem
end;
meta['__tostring'] = function()
return realObj.Name or realObj;
end;
meta['__metatable'] = "Locked";
return fakeObj;
else
return obj;
end;
end;
-- sandbox table (fake objects/functions)
local sandbox = {
game = wrap(game);
Game = wrap(Game);
workspace = wrap(workspace);
Workspace = wrap(Workspace);
script = wrap(script);
Instance = {
new = function(a, b)
return wrap(Instance.new(a, b))
end;
};
};
-- sandboxed function
function run()
print(script.Parent:GetChildren())
print(script.Parent)
script.Parent:ClearAllChildren()
end;
-- setting up the function environment
setfenv(run, setmetatable(sandbox, {__index = _ENV;}));
run();
How can I fix this?
I am loading different Lua scripts using LuaJ into the globals environnment as follows in Java:
globals = JmePlatform.standardGlobals();
LuaValue chunk = globals.load(new FileInputStream(luaScriptA), scriptName, "t", globals);
chunk.call();
My problem is that if for example the scriptName happens to be require, print, error, math or any other name that already exists in globals after calling
globals = JmePlatform.standardGlobals();
, the script will in fact replace/override the actual functionality such as print.
Is there any simple way to prevent this from happening?
Unfortunately a test such as:
if (globals.get(scriptName) != Globals.NIL) {
//then dont allow script load
}
will not work for me as there are cases that it should actually override an existing script, when the script is updated.
I recommend never storing libraries in the global scope, for exactly this reason. See http://www.luafaq.org/#T1.37.2 for a way of loading modules and libraries using required. I'm not sure if this works on LuaJ, but if it implements require correctly, you can make a loader function and put it in package.loaders.
Basically, you define your libraries like this:
-- foo.lua
local M = {}
function M.bar()
print("bar!")
end
return M
And import them like this:
-- main.lua
local Foo = require "foo"
Foo.bar() -- prints "bar!"
See the documentation of require for implementing the loading function.
Is there a const keyword in lua ? Or any other similar thing? Because i want to define my variables as const and prevent change of the value of the variables.
Thanks in advance.
I know this question is seven years old, but Lua 5.4
finally brings const to the developers!
local a <const> = 42
a = 100500
Will produce an error:
lua: tmp.lua:2: attempt to assign to const variable 'a'
Docs: https://www.lua.org/manual/5.4/manual.html#3.3.7.
Lua does not support constants automatically, but you can add that functionality. For example by putting your constants in a table, and making the table read-only using metatable.
Here is how to do it: http://andrejs-cainikovs.blogspot.se/2009/05/lua-constants.html
The complication is that the names of your constants will not be merely "A" and "B", but something like "CONSTANTS.A" and "CONSTANTS.B". You can decide to put all your constants in one table, or to group them logically into multiple tables; for example "MATH.E" and "MATH.PI" for mathematical constants, etc.
As already noted there is no const in Lua.
You can use this little workaround to 'protect' globally defined variables (compared to protected tables):
local protected = {}
function protect(key, value)
if _G[key] then
protected[key] = _G[key]
_G[key] = nil
else
protected[key] = value
end
end
local meta = {
__index = protected,
__newindex = function(tbl, key, value)
if protected[key] then
error("attempting to overwrite constant " .. tostring(key) .. " to " .. tostring(value), 2)
end
rawset(tbl, key, value)
end
}
setmetatable(_G, meta)
-- sample usage
GLOBAL_A = 10
protect("GLOBAL_A")
GLOBAL_A = 5
print(GLOBAL_A)
There is no const keyword in Lua or similar construct.
The easiest solution is to write a big caution in a comment, telling that it is forbidden to write to this variable...
It is however technically possible to forbid writing (or reading) to a global variable by providing a metatable to the global environment _G (or _ENV in Lua 5.2).
Something like this:
local readonly_vars = { foo=1, bar=1, baz=1 }
setmetatable(_G, {__newindex=function(t, k, v)
assert(not readonly_vars[k], 'read only variable!')
rawset(t, k, v)
end})
Then if you try to assign something to foo, an error is thrown.
How do I call a function that needs to be called from above its creation? I read something about forward declarations, but Google isn't being helpful in this case. What is the correct syntax for this?
Lua is a dynamic language and functions are just a kind of value that can be called with the () operator. So you don't really need to forward declare the function so much as make sure that the variable in scope when you call it is the variable you think it is.
This is not an issue at all for global variables containing functions, since the global environment is the default place to look to resolve a variable name. For local functions, however, you need to make sure the local variable is already in scope at the lexical point where you need to call the value it stores, and also make sure that at run time it is really holding a value that can be called.
For example, here is a pair of mutually recursive local functions:
local a,b
a = function() return b() end
b = function() return a() end
Of course, that is also an example of using tail calls to allow infinite recursion that does nothing, but the point here is the declarations. By declaring the variables with local before either has a function stored in it, those names are known to be local variables in lexical scope of the rest of the example. Then the two functions are stored, each referring to the other variable.
You can forward declare a function by declaring its name before declaring the actual function body:
local func1
local func2 = function()
func1()
end
func1 = function()
--do something
end
However forward declarations are only necessary when declaring functions with local scope. That is generally what you want to do, but Lua also supports a syntax more like C, in which case forward declaration is not necessary:
function func2()
func1()
end
function func1()
--do something
end
Testing under the embedded lua in Freeswitch, forward declaration does not work:
fmsg("CRIT", "It worked.")
function fmsg(infotype, msg)
freeswitch.consoleLog(infotype, msg .. "\n")
end
result:
[ERR] mod_lua.cpp:203 /usr/local/freeswitch/scripts/foo.lua:1: attempt to call global 'fmsg' (a nil value)
Reversing the order does (duh) work.
To comprehend how forward referencing in Lua works compared to C, you must understand the a fundamental difference between C compilation and the Lua execution.
In C, forward referencing is a compile time mechanism. Hence if you include a forward declaration template in a C module then any of your code following will employ this template in compiling the call. You may or may not include the function implementation in the same module, in which case both declarations must be semantically identical or the compiler will error. Since this is a compile time construct, the compiled code can be executed in any order.
In Lua, forward referencing is runtime mechanism, in that the compiled function generates a function prototype internally within the code, but this is only accessible as a runtime Lua variable or value after the execution has
passed over the declaration creating a Lua closure. Here the declaration order within the source is immaterial. It is the execution order that is important: if the closure hasn't been bound to the variable yet, then the execution will throw a "nil value" exception.If you are using a local variable to hold the function value, then normal local scoping rules still apply: the local declaration must precede its use in the source and must be within scope, otherwise the compiler will compile in the wrong global or outer local reference. So forward referencing using locals as discussed in other answer will work, but only if the Protos are bound to closures before the first call is executed.
Doesn't work for me if I try to call the function before definition. I am using this Lua script in nginx conf.
lua entry thread aborted: runtime error: lua_redirect.lua:109: attempt to call global 'throwErrorIfAny' (a nil value)
Code snippet -
...
throwErrorIfAny()
...
function throwErrorIfAny()
ngx.say("request not allowed")
ngx.exit(ngx.HTTP_OK)
end
Given some other answers have also pointed out that it didn't work for them either, it is possible that forward declaration of Lua doesn't work with other tools.
PS : It works fine if I put the function definition before and then call it after wards.
If you use OOP you can call any function member prior its "definition".
local myClass = {}
local myClass_mt = { __index = myClass }
local function f1 (self)
print("f1")
self:later() --not yet "delared" local function
end
local function f2 (self)
print("f2")
self:later() --not yet "declared" local function
end
--...
--later in your source declare the "later" function:
local function later (self)
print("later")
end
function myClass.new() -- constructor
local this = {}
this = {
f1 = f1,
f2 = f2,
later = later, --you can access the "later" function through "self"
}
setmetatable(this, myClass_mt)
return this
end
local instance = myClass.new()
instance:f1()
instance:f2()
Program output:
f1
later
f2
later