Lua uses the time service provided by the operating system. The available resolution is usually not very high and it's perceived as time jumps at Lua level. Imagine a wall clock with minute resolution. It cannot be used to measure millisecond intervals....
There is no extension to the Lua C API to access cdata objects as created by LuaJIT's FFI library. So, the simple and recommended way is to do your marshalling from the Lua side if you're dealing with cdata. So, call a C function from Lua and pass that cdata...
x, y, z= angles() print (x,y,z) ...
lua,neural-network,backpropagation,training-data,torch
why the predictionValue variable is always the same? Why doesn't it get updates? First of all you should perform the backward propagation only if predictionValue*targetValue < 1 to make sure you back-propagate only if the pairs need to be pushed together (targetValue = 1) or pulled apart (targetValue =...
You don't use math.random to select a function; you use it to pick a random number, which you can then use as an index to get the function you need from a table (as one example): local list = { function() print(1) end, function() print(2) end, function() print(3) end }...
To fully understand the display.newText api of Corona SDK you can view it here: https://docs.coronalabs.com/api/library/display/newText.html For the Tap event you can view it here: https://docs.coronalabs.com/api/event/tap/index.html But I have fixed your code for you. But I really can't understand why you have "Impact" there. but here is a working code you...
There are several misunderstandings of how TeX works. Your \compare macro wants to find something followed by a comma, then something followed by a period. However when you call \compare\test no comma is found, so TeX keeps looking for it until finding either the end of file or a \par...
From C++, you could call luaL_dofile with the path to your file directly, then just call the function the usual way.
function,variables,lua,arguments
Change: return tbl[varname[index]] to: return tbl[varname][index] ...
local options = {} [#options+1] = 'images/shop1price.png' [#options+1] = 'images/shop2price.png' [#options+1] = 'images/shop3price.png' local priceTag = {} for i = 1,#options do priceTag[i] = widget.newButton{ defaultFile = options[i], overColor = {128,128,128,255}, width = 73, height = 38, left = (centerX-155) + (i-1)*118, top = centerY*0.88, id = i, onEvent...
action = { [1] = function (x) print(1) end, [2] = function (x) z = 5 end, ["nop"] = function (x) print(math.random()) end, ["my name"] = function (x) print("fred") end, } You are free to do that....
Looks like a syntax error. message.Destroy() should be message:Destroy() according to this Roblox wiki page http://wiki.roblox.com/index.php?title=API:Class/Instance/Destroy Also see the section Explosions, Messages, and More at URL http://wiki.roblox.com/index.php?title=Basic_Scripting which provides similar syntax using the colon (:) operator....
You found a variant of the Multi-dimensional Knapsack Problem, which is known to be NP-complete. So no, there is no simple "best" solution, however, a number of strategies have been found to yield acceptable results in acceptable time. Please see the linked article for further explanation.
c++,arrays,lua,arguments,lua-table
The stack index -2 is the second to top element of the lua C stack. The arguments to your lua C function are also on the stack. So when you get two arguments your stack is <table>, <number> then you push a nil value and your stack is <table>, <number>,...
You can't. The Lua C API and the LuaJIT FFI are deliberately separated and cannot interact. Rewrite PrintC in Lua using the FFI, or write Lua C API bindings to the library you're using p with. I.e. Use one or the other....
Using == for functions only checks if they reference to the same function, which is not what you expected. This task is rather difficult, if not impossible at all. For really simple cases, here's an idea: function f(x) return x + 1 end local g = function(y) return y +...
If you want to move sideways, you can simply add or subtract 90 degrees (in radians, that is π/2) from your r before calculating the sin/cos velocity vector.
lua,geometry,corona,geometry-surface
This sample from caronalabs.com forums shows how you might draw an arc, which provides the discrete algorithm you would need to do what you're asking: function display.newArc(group, x,y,w,h,s,e,rot) local theArc = display.newGroup() local xc,yc,xt,yt,cos,sin = 0,0,0,0,math.cos,math.sin --w/2,h/2,0,0,math.cos,math.sin s,e = s or 0, e or 360 s,e = math.rad(s),math.rad(e) w,h =...
I finally got it to work (some other errors were getting in the way). The aforementioned line copies the generated luaconf.h file to the binary directory, now instead I just copy it to the source directory: configure_file ( src/luaconf.h.in ${CMAKE_CURRENT_SOURCE_DIR}/src/luaconf.h ) ...
Hi sid here you go: _W = display.contentWidth; _H = display.contentHeight; local button = {} x = -20 for count = 1,3 do x = x + 90 y = 20 for insideCount = 1,3 do y = y + 90 button[count] = display.newImage("imgs/one.png"); button[count].x = x; button[count].y = y;...
It is a preprocessor macro lib/TH/THTensor.h: #define THTensor_(NAME) TH_CONCAT_4(TH,Real,Tensor_,NAME) which leads to... lib/TH/THGeneral.h.in: #define TH_CONCAT_4(x,y,z,w) TH_CONCAT_4_EXPAND(x,y,z,w) and finally... lib/TH/THGeneral.h.in: #define TH_CONCAT_4_EXPAND(x,y,z,w) x ## y ## z ## w Therefore, long THTensor_(storageOffset)(const THTensor *self) ultimately becomes this: long THRealTensor_storageOffset(const THTensor *self) Aren't preprocessors just grand ?...
c,lua,neural-network,luajit,torch
I can't find a way to convert or write to a file the Torch Tensors to make them readable in C. Ideally, I want to convert the Tensors into arrays of double in C. The most basic (and direct) way is to directly fread in C the data you...
You can use the following function to extract a list of columns: function cols(t, colnums, prefix) -- get the number of the first column and the rest of the numbers -- it splits 1,2,3 into 1 and 2,3 local col, rest = colnums:match("^(%d+)[,%s]*(.*)") -- if nothing is provided return current...
You can use a subprocess to run your Lua script and provide the function with it's arguments. import subprocess result = subprocess.check_output(['lua', '-l', 'demo', '-e', 'test("a", "b")']) print(result) result = subprocess.check_output(['lua', '-l', 'demo', '-e', 'test2("a")']) print(result) the -l requires the given library (your script) the -e is the code that...
One thing you could do is make a table of words you want to look for, then use gmatch to iterate each word in the string and check if it's in that table. #!/usr/bin/env lua function matchAny(str, pats) for w in str:gmatch('%S+') do if pats[w] then return true end end...
The following Lua library provides functions to (asynchronously) start and monitor processes. http://stevedonovan.github.io/winapi/...
I don't see why using the date table as keys. You can instead use the timestamp directly as keys, something like: t[os.time()] = somevalue The timestamps are only integer values, you can get its real date with os.date when in need. You can compare them directly. For instance, to remove...
You may utilize integer part of the table to store keys in order: function add(t, k, v, ...) if k ~= nil then t[k] = v t[#t+1] = k return add(t, ...) end return t end t = add({ }, "A", "hi", "B", "my", "C", "name", "D", "is") for i,k...
You need to call lua_next(L,-2) after lua_pushnil(L). You need lua_next because apparently you don't know the key in the table. So you have to use the table traversal protocol, which is to push the table, push nil, call lua_next(L,-2), and get the key and value on the stack. This works...
Functions can be stored in variables (both global and local) and in tables, can be passed as arguments, and can be returned by other functions. When we talk about a function name, such as print, we are actually talking about a variable that holds that function. a = {p =...
That library (and the one which it depends on) have no versioned release yet, so they are marked as DEV (which you can see in the "Versions" section). Those libraries do not show up in searches or can't be installed by default. You need to add the "development" repository in...
You can just call both at same time in a single transition. Just like: local rect = display.newRect(300,100,50,50) -- Create object transition.to(rect, {x=-250, rotation = rect.rotation-360,time=2000,} ) -- Transition call ...
To check if the table jsonRequest contains the key "object", use: if jsonRequest.object ~= nil then If the values stored in the table won't be the boolean value false, you can also use: if jsonRequest.object then ...
Some more details, based on EgorSkriptunoff answer. So, that Lua code works just fine for me to get OLE Automation date in lua: -- number of days between December, 30 1899 and January, 1 1970 local magicnumber = 25569 -- don't forget about time zone (UTC+3 for my case) local...
nginx,lua,luajit,luasocket,luarocks
smtp.send uses LuaSocket's socket.protect function for handling internal errors. This function is implemented in C and doesn't allow yielding in the current releases (the version in git HEAD now allows yielding on Lua 5.2+, see discussion here). Apparently someone tries to yield from within it. In etc/dispatch.lua in the LuaSocket...
You are looking for string.char: string.char (···) Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument. Note that numerical codes are not necessarily portable across platforms. For your example:...
You can always use NetworkManager which is available for installation in most official repos. It contains an applet which creates an icon at your system tray. You can launch the applet at start-up, placing this line in your rc.lua file: awful.util.spawn("nm-applet") or you can start it manually from your terminal,...
If you want to avoid typing, see if your editor can expand ++i to i = i + 1 for you. If you just want a hacky way that doesn't involve modifying the Lua source code then tables will get you pass-by-reference and the __call meta-method can be used as...
local function Rotate(X, Y, alpha) local c, s = math.cos(math.rad(alpha)), math.sin(math.rad(alpha)) local t1, t2, t3 = X[1]*s, X[2]*s, X[3]*s X[1], X[2], X[3] = X[1]*c+Y[1]*s, X[2]*c+Y[2]*s, X[3]*c+Y[3]*s Y[1], Y[2], Y[3] = Y[1]*c-t1, Y[2]*c-t2, Y[3]*c-t3 end local function convert_rotations(Yaw, Pitch, Roll) local F, L, T = {1,0,0}, {0,1,0}, {0,0,1} Rotate(F, L, Yaw)...
The bug is in lua_next(L, -2) line, because -2 refers to stack top minus one, which happens here to be the last argument to print. Use lua_next(L, i) instead. Upd: Lua stack indexes are subject to float when moving code around at development stage, so the general advice is to...
You should push 1 and 2 on to the stack (or 0,1 if tables are 0indexed) and use lua_geti instead of iterating over the table with lua_next. Another example of how your current code is incorrect is what happens if the Lua user passes {1, 2, 3}? You would be...
function foo(param_1, param_2) -- obtain the default values local p1, p2 = getBar() -- combine the provided values with default values local bar_1, bar_2 = (param_1 or p1), (param_2 or p2) -- do whatever you need with bar_1 and bar_2 end If the getBar function call is expensive and should...
Because that's what table.concat is documented as doing. Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ··· sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i...
As far as I understand, you can't create that socket using mkfifo (or any command) as it will be created by the (listening) server. There is an example listed on the same page you referenced, but it may be difficult to find: sock, err = s:listen([backlog|_32_]) sock, err = s:bind(path)...
x[x:gt(5)] = 0 In general there are x:gt :lt :ge :le :eq There is also the general :apply function tha takes in an anonymous function and applies it to each element....
luajit is not lua 5.3. You cannot mix runtimes. You have a version of luasocket built for lua 5.3 but you are running luajit 2.1....
Usually, the only things that would trigger a sort of tick, or cause a sizable amount of stoppage for a tick to pass by is pulling events (os.pullEvent,os.pullEventRaw,coroutine.yield) turtle movement does of course need a tick to go by, and do call coroutine.yield to pause the script and move. The...
Simple detouring is easy to do with closures; no need for loadstring: function detour(cls) local detours = {} for key, value in pairs(cls) do if type(value) == "function" then -- note: ignores objects with __call metamethod detours["custom_detour_"..key] = function(...) -- Do whatever you want here return value(...) end end end...
I know nothing about NodeMCU but that is not a proper http server. For it to properly work with a browser, it should return some headers. You can try to close the connection after sending the response. Try the following: wifi.setmode(wifi.STATION) wifi.sta.config("SSID", "password") wifi.sta.connect() srv = net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive", function(conn,...
Broken down, it works like this. local dev Not really needed, but I'd imagine you know it creates local variable dev. for _, dev in ipairs(devices) do Loops through indexed table devices, and stores the value into dev locally. local net Again, not really needed. for _, net in ipairs(dev:get_wifinets())...
Ok, I managed to find a solution for the filled ellipse by checking if the pixel from the second half is gonna be drawn in the x-range of the first half of the ellipse. function drawellipse(xc, yc, w, h, dofill) --trouble with the size, 1 pixel to large on x...
In Lua, the order that pairs iterates through the keys is unspecified. However you can save the order in which items are added in an array-style table and use ipairs (which has a defined order for iterating keys in an array). To help with that you can create your own...
for-loop,lua,iterator,lua-table
You are creating the record table before creating the bid# tables. So when you do record = {bid1, bid2, bid3} none of the bid# variables have been created yet and so they are all nil. So that line is effectively record = {nil, nil, nil} which, obviously, doesn't give the...
It's a bit odd to use malloc instead of new, but it is possible. You need to use placement new: void *memory = malloc(sizeof(Estructura)); Estructura *est = new(memory)Estructura; When you're finished with the object it's your responsibility to call the destructor yourself: est->~Estructura(); Everything, such as vtables, will be correctly...
I had a similar task, and solved it by launching a new script for the outbound leg. When the outbound leg is answered, I send uuid_break to the inbound leg, and let the channels bridge together. It's done in Perl, but Lua should be quite similar: https://github.com/xlab1/freeswitch_secretary_bug (the scripts are...
It's better to avoid working with slopes and angles if you can avoid them, because you will have to deal with annoying special cases like when the slope is +ve or -ve infinity and so on. If you can calculate the normal of the line (blue arrow), then you can...
The arguments for g++ had -llua before the input file. I put -llua at the end, and everything works fine now.
I still have to read the entire docs, but already found this: There are 16384 hash slots in Redis Cluster, and to compute what is the hash slot of a given key, we simply take the CRC16 of the key modulo 16384. There is a command for that op already:...
c,multithreading,lua,erlang,ffi
If you can make the Lua code — or more accurately, its underlying native code — cooperate with the Erlang VM, you have a few choices. Consider one of the most important functions of the Erlang VM: managing the execution of a (potentially large number of) Erlang's lightweight processes across...
Yes, you can use compat-5.3 to get many of the newer lua C API functions in lua 5.1 (and 5.2). The particular function you're looking for (luaL_requiref) you can find here...
You're missing a period between tbl.a and __index. __index needs to be on a's metatable, not the table itself. You don't return anything from your __index function self in the __index function is the table being indexed, not the key (which is the second argument) This should work: setmetatable(tbl.a,...
Characters and bytes are two different things. Characters can be encoded in bytes in various ways, using different encodings. One possible encoding is UTF-8. Unfortunately Lua's string.match doesn't know almost anything about charactes and encodings, it only works with bytes. So your script is not looking for the "V", "c",...
Short answer you can't. But, you can run an URL decode after logrotate. Here is the command : awk -v RS='\\\\x[0-9]{2}' 'RT{ORS=sprintf("%c", strtonum("0" substr(RT, 2)))} 1' ...
vb.net,lua,draw,pixels,ellipse
Here's what I came up with for my CPU renderer in the past. It's very efficient and very simple too. It relies on the mathematical definition of the ellipse, so the ellipse is drawn centered at x,y and has the width and height defined from the center, not from the...
One way is to use another index table: local index = {"red", "green", "blue", "purple", "pink", "yellow"} Then you can use colors[index[count % 6 + 1]]. The downside is, if the keys of colors are modified, index needs to be updated manually....
Open a command line (e.g. under windows, that's cmd). Go into the directory where you have your local copy of XFuscator. Make sure lua is on your PATH. Type lua XFuscator.lua -h This should show the help message, which will describe the next steps....
The problem is the convolutional neural network from this tutorial has been made to work with a fixed size input resolution of 32x32 pixels. Right after the 2 convolutional / pooling layers you obtain 64 feature maps with a 5x5 resolution. This gives an input of 64x5x5 = 1,600 elements...
There is Jan Kneschke's lua magnet of which I maintain a fork on github. I use this in conjunction with FastCGI (and luasql.sqlite3) for a small message board, which was previously written in PHP, then python. The PHP and python versions each performed so-so (which may be due to me...
Since MyClass is just a lookup in the global table (_G), you could mess with its metatable's __index to return a newly-defined MyClass object (which you would later need to fill with the details). However, while feasible, such an implementation is wildly unsafe, as you could end up with an...
You could insert a userdata into io.stdin/stdout/stderr using lua_getglobal(L, "io"); lua_pushlightuserdata(L, …); // or whatever value you want here lua_setfield(L, 0, "stdin"); // rinse, repeat for stdout and stderr ...
Compiling lua for nginx has some specifics. You could see details on official Lua module page http://wiki.nginx.org/HttpLuaModule#Lua.2FLuaJIT_bytecode_support
I'm not entirely sure if you are hung up on the syntax or the algorithmic part of this problem. I figure the syntax is simpler to look up so I will offer the simple calculation. Your tuple will be calculated using the lua math functions: math.rad, math.cos, math.sin {math.cos(math.rad(degrees)), math.sin(math.rad(degrees))}...
lua,conflicting-libraries,luarocks
Not a command line option, but you may have different variants of the LuaRocks command line program available (luarocks-5.1 and luarocks-5.2) if you installed LuaRocks for both Lua versions. You can do so from source using (assuming a Debian/Ubuntu-like lua5.1 executable): ./configure --lua-version=5.1 --lua-suffix=5.1 --versioned-rocks-dir # make sure that you...
for-loop,matrix,lua,deep-learning,torch
See the documentation for the Tensor:apply These functions apply a function to each element of the tensor on which the method is called (self). These methods are much faster than using a for loop in Lua. The example in the docs initializes a 2D array based on its index i...
This is not a problem of Lua itself. > print("bisción" == "bisción") true Perhaps there is a discrepancy between the character encoding used by your source code editor, and by your data sources. Lua makes the compare operation at byte level. It's enough to have the Lua source file encoded...
local subst = { U = "üûùÜú", N = "ñÑπⁿ∩", O = "ôöòÖóºσΘΩ°", I = "ïîìí¡│", F = "⌠", A = "âäàåÄÅæÆáª╡╢╖╞╟α", E = "éëèÉΣ", } local subst_utf8 = {} for base_letter, list_of_letters in pairs(subst) do for utf8letter in list_of_letters:gmatch'[%z\1-\x7F\xC0-\xFF][\x80-\xBF]*' do subst_utf8[utf8letter] = base_letter end end function processstring(instr) return (instr:upper():gsub('[%z\1-\x7F\xC0-\xFF][\x80-\xBF]*',...
When called without arguments, io.read() reads a whole line. You could read the line and get the words using pattern matching: input = io.read() opr, txt = input:match("(%S+)%s+(%S+)") The above code assumes that there is just one word for opr and one word for txt. If there might be zero...
Set the corresponding environment variable or rebuild Lua after adding your path to the source.
It looks as though you are not even using the X var... so why don't you try this... this is a more effective way to keep doing the same thing over and over while true do getTarg() derp1() sleep(2.9) monInit() end ...
if c.class == "Google-chrome" then local icon = gears.surface("path/to/chrome.png") return text, bg, bg_image, icon end Add this code before if capi.client.focus == c then ...
http://lua-users.org/wiki/MathLibraryTutorial upper and lower must be integer. In other case Lua casts upper into an integer, sometimes giving math.floor(upper) and others math.ceil(upper), with unexpected results (the same for lower). ...
If you are using Lua 5.1 then I believe you need to wrap your desired function call in another function (that takes no arguments) and use that in the call to xpcall. local function f (a,b) return a + b end local function err (x) print ("err called", x) return...
The purpose of this Lua function is only to provide a unique name. There are not many options in the standard Lua library. In other words, either you use what's available in Lua, or you write your own function. However, even if you use hashes, random numbers, and so...
I have solved this issue with the following code: local ffi = require "ffi" ffi.cdef[[ typedef struct { char *fpos; void *base; unsigned short handle; short flags; short unget; unsigned long alloc; unsigned short buffincrement; } FILE; FILE *fopen(const char *filename, const char *mode); int fprintf(FILE *stream, const char *format,...
osx,lua,osx-yosemite,libpng,torch
I had a similar problem (OSX 10.9.5). You probably have multiple versions of libpng installed, with the one called during install of luarocks having architecture i386 (x86_64 required). To solve this: Try installing image again, and reading the log: luarocks install image Check the log to see if you get...
lua,pattern-matching,string-matching
This pattern works: "2%.0%.0%.%d%d%d" ...
Is there a way to manually disable omp usage in some cases (but not always)? If you really want to do that one possibility is to use torch.setnumthreads and torch.getnumthreads like that: local nth = torch.getnumthreads() torch.setnumthreads(1) -- do something torch.setnumthreads(nth) So you can monkey-patch nn.LogSoftMax as follow: nn.LogSoftMax.updateOutput...
You are inserting the pipes when the table has more than one element. Your original code is effectively this (for the single battery case): local output={} table.insert(output, "a") print(table.concat(output, "|")) # a Your uncommented version of the code is effectively this: local output={} table.insert(output, "pre-a") table.insert(output, "a") table.insert(output, "post-a") print(table.concat(output,...
You are confusing values and variables. Values have data types like string, table, function, etc. Call the type function on an expression to get its type. Variables refer to values but don't have a data type. The categories you are referring to: global, local and table field are not data...
Using a nested loop works. for lk, lv in ipairs(list) do for dk, dv in ipairs(database) do if string.find(dv.serial, tostring(lv)) then table.insert(copy, dv.img) end end end I'm using ipairs, which is similar to for i=1, #list do....