I’m trying to create a table that is dynamically populated with the on/off status of set of switches I have. The following is where I I’ve got stuck as it always returns nothing/nil? ..
-- retrieved http.request status of 4 binary switches
local P61v = 1
local P62v = 0
local P63v = 1
local P64v = 0
— following table should allow us to look up the status of all associated light by their plug names P61, P62, P63 etc.
local LookupTable = {
P61 = P61v,
P62 = P62v,
P63 = P63v,
P64 = P64v
}
local x = LookupTable[P62]
print(x)
In LookupTable[P62] the expression P62 is evaluated to nil, resulting in LookupTable[nil] which resolves to nil.
What you are looking for is either
LookupTable.P62
-- or --
LookupTable['P62']
which are equivalent ways of expressing the same thing.
I created a script that defines both values, and this is what I ended up with..
local PowerResponse = "P61=0,P62=1,P63=0,P64=0"
local P61, _, P61v, P62, _, P62v, P63, _, P63v, P64, _, P64v = PowerResponse:match("(%w*)(=)(%d),(%w*)(=)(%d),(%w*)(=)(%d),(%w*)(=)(%d)")
local PowerStatusTable = {
P61 = P61v,
P62 = P62v,
P63 = P63v,
P64 = P64v
}
--local x = PowerStatusTable[P62]
for k, v in pairs(PowerStatusTable) do
luup.variable_set("urn:upnp-net:serviceId:IPPower1", k, v,deviceID)
end
Related
local R = script.Parent.R.Text
local G = script.Parent.G.Text
local B = script.Parent.B.Text
script.Parent.ColorIndicator.BackgroundColor3 = Color3.fromRGB(R, G, B)
Ok, so how do I make this work? I'm making a Building Tools like thing that would let you customize the color, and I want it to work by using the Text value of a TextBox to change the color of the part that would be created, any help will do.
All Instances come with a GetPropertyChangedSignal function that you can utilize to update the color anytime the text changes.
-- find the UI elements
local R = script.Parent.R
local G = script.Parent.G
local B = script.Parent.B
local Indicator = script.Parent.ColorIndicator
local function clamp(minimum, value, maximum)
return math.max(minimum, math.min(value, maximum))
end
local function updateColor(newValue)
-- use pcall to safely try and update the colors
local success, result = pcall(function()
-- try to convert the text to numbers
local r = tonumber(R.Text) or 0
local g = tonumber(G.Text) or 0
local b = tonumber(B.Text) or 0
-- limit numbers to a valid range
local clampedR = clamp(0, r, 255)
local clampedG = clamp(0, g, 255)
local clampedB = clamp(0, b, 255)
-- set the color
Indicator.BackgroundColor3 = Color3.fromRGB(clampedR, clampedG, clampedB)
end)
if not success then
warn("Failed to update colorIndicator with error : ", result)
end
end
-- listen for changes on each of the text boxes
R:GetPropertyChangedSignal("Text"):Connect(updateColor)
G:GetPropertyChangedSignal("Text"):Connect(updateColor)
B:GetPropertyChangedSignal("Text"):Connect(updateColor)
There is more you could do to prevent the user from entering text that is not numbers, like checking the newValue string for non-numerical characters and removing them... but that seems beyond what you're asking here.
As you can tell I'm a beginner in lua. I am trying to understand a function I'm stuck at what the following code segment does?
It is used in the following code snippet in the last line:
function classify(txt_dir, img_dir, cls_list)
local acc = 0.0
local total = 0.0
local fea_img = {}
local fea_txt = {}
for fname in io.lines(cls_list) do
local imgpath = img_dir .. '/' .. fname .. '.t7'
local txtpath = txt_dir .. '/' .. fname .. '.t7'
fea_img[#fea_img + 1] = extract_img(imgpath)
fea_txt[#fea_txt + 1] = extract_txt(txtpath)
end
for i = 1,#fea_img do
-- loop over individual images.
for k = 1,fea_img[i]:size(1) do
local best_match = 1
local best_score = -math.huge
for j = 1,#fea_txt do
local cur_score = torch.dot(fea_img[i][{k,{}}], fea_txt[j])
From my understanding, fea_img is a lua table. Is the line fea_img[i][{k,{}}] some sort of slicing for the value for the key 'i' in the table fea_img?
I tried searching for more examples and found this being used here too (last line):
for i = 1,nsamples,batchsize do
-- indices
local lasti = math.min(i+batchsize-1,nsamples)
local m = lasti - i + 1
-- k-means step, on minibatch
local batch = x[{ {i,lasti},{} }]
Any help on this would be really appreciated. Thank you!
In lua you can access a specific index on a table in multiple ways. Like these two examples
local myValue = someTable.theIndex
-- or
local myOtherValue = someTable[2]
So the construct you see here is to access some values from a (nested) table.
Also in lua you can use anything except nil as a index, so even tables are possible.
The line
fea_img[i][{k,{}}]
Can be extended to this:
local index1 = i -- i in this case is your loop variable
local index2 = { k , { } } -- This creates a table with 2 values, the first one will be the vaule of the var k, the second one is an empty table
local value1 = fea_img[index1] -- This will get you a table
local value2 = value1[index2] -- This will get the same as: fea_img[i][{k,{}}]
Correction and Addition:
As Nicol Bolas already said in the comments: The index must be an exact match. Which means it literally has to be the same table, which is not the case for the presented code from you. Either you dropped code you thought is unnecessary or fea_img has some some kind of metatable on it.
In the case of
local k = 2
local table1 = {k, { } }
local table2 = {k, { } }
table2 and table1 do have the exact same content. But they are not the same table. Which will lead to nil always being retrieved if one is used to store data in a table and the other is used to get it back.
Syntactically, t[k] is indexing a table with a key. Normally, if there is a record in the table with the key k, its value is returned. Nothing more, nothing less.
If fea_img[i] was a normal table, {k,{}} would always return nil, since table indices are resolved based on their identity ({k,{}} is always a new table). Based on your code, I have to conclude that the elements of fea_img (i.e. what extract_img returns) are not normal tables.
In Lua, you can override the indexing operation using a metatable. If you index a value that has a metatable with __index, it will be used if there is no matching record in the table:
local t = {}
setmetatable(t, {
__index = function(t, k)
return k
end
})
print(t[{}])
This table has a metatable associated with it, which is used in the indexing operation. In this case __index returns the key, but whatever library you are using might provide more complex behaviour.
This is specific to the library you are using, not something related to the Lua syntax.
I'm going to simplify the situation as much as I can. I have the following code:
windows = { "window1", "window2" }
window1 = {
x = 100
y = 100
properties = { active = false, width = 200, height = 200 }
}
window2 = {
x = 0
y = 0
properties = { active = false, width = 200, height = 200 }
}
If I do the following, I get the correct output:
print (window1.x)
OUTPUT: 0
print (window1.properties.active)
OUTPUT: false
HOWEVER, if I iterate through the list, I get "nil" values for "l.x" and "l.properties.active":
for _,l in ipairs(windows) do
print (l)
print (l.x)
print (l.properties.active)
end
Is there a different way I need to iterate through the variables in the lists, so I can get the values?
That is not a nested table, but just a table containing strings. And, as you just saw, a string doesn't contain a value for the key "x".
You have to put the tables in a sequence:
local window1 = {...} -- first table
local window2 = {...} -- second table
local windows = {window1, window2}
for _,l in ipairs(windows) do
-- do stuff with l
end
Or, if you want to keep the list of strings and iterate over the strings, put the windows in a second table using these strings as a key.
local windowNames = { "window1", "window2" }
local windows = {}
windows.window1 = {...} -- first table
windows.window2 = {...} -- second table
for _,l in ipairs(windowNames) do
local ourWindow = windows[l]
-- do stuff with ourWindow
end
Right now I'm trying to use Lua to receive variables from barcodes sent out from an outside source. When I run this, there is a variable rotation from the local function rot(input) that appears to be "buggy". If I run this code exactly as it is with the print statements below, the rotation will appear and disappear. Please help me understand why this may happen?
Please note: There are two aspects of this code that I'm currently working on. A) Code128 is not properly retrieving the variables. B)My code can definitely be shortened. But I'm new and learning as I go. The main purpose for this thread is to help me understand why code will sometimes display the desired result, then won't the next minute?
Thank you.
Edited: I've updated the code a bit to make it cleaner. Condensed all of my string.match statements into tables with other barcode related fields. Still learning and looking to make it even more cleaner. I love learning this, but am still having the same problem with my local function rot(input) and getting intermittent results. Any help is greatly appreciated!
local function rot(input)
rotTable = {["R"] = "cw", ["I"] = "180", ["B"] = "ccw"}
for k,v in pairs (rotTable) do
if input == k then
rotation = v
else
rotation = ""
end
end
return rotation
end
local function barCode(input)
local bcID = string.match(input,"%^(B%w)")
if bcID == "BY" then
bcID = string.match(input,"%^BY.*%^(B%w)")
end
local bcTable = {
["BC"] = {"code128", 10, string.match(input,"%^BY.*%^BC(%u),(%d*),(%u),%u,%u%^FD(.*)%^FS")},
["B2"] = {"bc2of5i", 20, string.match(input,"%^B2(%u),(%d*),(%u),%u,%u%^FD(.*)%^FS")},
["BE"] = {"ean13", 10, string.match(input,"%^BE(%u),(%d*),(%u),%u%^FD(.*)%^FS")},
["B8"] = {"ean8", 10, string.match(input,"%^B8(%u),(%d*),(%u),%u%^FD(.*)%^FS")},
["B3"] = {"code39", 10, string.match(input,"%^B3(%u),%u,(%d*),(%u),%u%^FD(.*)%^FS")},
["BU"] = {"upc_a", -1, string.match(input,"%^BU(%u),(%d*),(%u),%u%,%u^FD(.*)%^FS")}
}
for k,v in pairs (bcTable) do
if bcID == k then
bcFields = v
bcType, qzone, bcR, bcH, bcHr, bcData = unpack(bcFields)
end
end
hPos = 0
vPos = 0
bcOutput = '<'..bcType..' qzone=\"'..qzone..'\" hbb=\"0\" vbb=\"0\" bbwidth=\"1\" hpos=\"'..hPos..'\" vpos=\"'..vPos..'\" rotation = \"'..rot(bcR)..'\" bgcolor=\"0\" barcolor=\"255\" textcolor=\"255\" barwidth=\"1\" height=\"8\">'..bcData..'</'..bcType..'>'
return bcOutput
end
print(barCode("^BY3^BCN,102,N,N^FDCHF05000042^FS"))
print(barCode("^B2B,110,N,N,N^FD45681382^FS"))
print(barCode("^BUN,183,N,N,N^FD61414199999^FS"))
print(barCode("^B8I,146,N,N^FD212345645121^FS"))
print(barCode("^BEB,183,N,N^FD211234567891^FS"))
I'm not sure what is wrong with your code, if anything, but rot can be written more simply as
local rotTable = {["R"] = "cw", ["I"] = "180", ["B"] = "ccw"}
local function rot(input)
return rotTable[input] or ""
end
In general, you shouldn't need to search Lua tables. For instance, the loop for k,v in pairs (bcTable) do can be replace by indexing as in the code above.
I've been trying to create a force-directed graphing algorithm with RBX::Lua. So far, everything seems to be working absolutely fine mathematically, but there are a couple of things that make absolutely no sense at all.
My problem is, the nodes experience an unexpected attraction to one another, whether connected or not. What the program does is, all of the unconnected nodes repel each other like a magnet, and all of the connected nodes attract each other like a spring.
I don't see anything in my code that could be causing this.
-- Creating an icon to represent each node
local n = Instance.new("Part", Instance.new("Humanoid", Instance.new("Model")).Parent)
n.Name = "Head"
local tor = Instance.new("Part", n.Parent)
tor.Name = "Torso"
tor.Anchored = true
tor.FormFactor = "Custom"
tor.Transparency = 1
local h = n.Parent.Humanoid
h.Health = 0
h.MaxHealth = 0
h.Parent.Name = "Node"
n.FormFactor = "Symmetric"
n.Shape = "Ball"
n.TopSurface, n.BottomSurface = "Smooth", "Smooth"
n.Size = Vector3.new(2,2,2)
n.BrickColor = BrickColor.new("Institutional white")
n.Anchored = true
Instance.new("Vector3Value", n).Name = "velocity"
-- List of connections and nodes
local t = {
["Metals"]={"Gold", "Silver", "Steel", "Brass", "Mercury"},
["Alloys"]={"Steel", "Brass"},
["Noble Gasses"]={"Helium", "Argon", "Krypton", "Xenon"},
["Water"]={"Hydrogen", "Oxygen"},
["Liquids"]={"Water", "Mercury"},
["Alone"]={}
}
--[[ -- Separate list for testing, commented out
local t = {
["A"]={"B"},
["B"]={"C"},
["C"]={"D"},
["D"]={"E"},
["E"]={"F"}
}]]
-- Add all of the nodes to the workspace, position them randomly
for _, v in pairs(t) do
local p1 = workspace:findFirstChild(_) or n.Parent:clone()
p1.Name = _
p1.Parent = workspace
p1.Head.CFrame = CFrame.new(Vector3.new(math.random(-100000,100000)/1000,0,math.random(-100000,100000)/1000))
for a, b in ipairs(v) do
if v ~= b then
local p2 = workspace:findFirstChild(b) or n.Parent:clone()
p2.Name = b
p2.Parent = workspace
p2.Head.CFrame = CFrame.new(Vector3.new(math.random(-100000,100000)/1000,0,math.random(-100000,100000)/1000))
local at = p1:findFirstChild(b) or Instance.new("ObjectValue", p1)
at.Name = b
local at2 = at:clone()
at2.Parent = p2
at2.Name = _
local lasso = Instance.new("SelectionPartLasso", p2.Head)
lasso.Name = "Link"
lasso.Humanoid = p2.Humanoid
lasso.Part = p1.Head
lasso.Color = BrickColor.new("Institutional white")
end
end
end
local parts = {} -- List of all of the nodes themselves
-- Add all of the nodes to the list
for _, v in ipairs(workspace:GetChildren()) do
if v.ClassName == "Model" then
table.insert(parts, v.Head)
end
end
while wait() do -- Repeat forever waiting one frame between loops
for _, v in ipairs(parts) do
for a, b in ipairs(parts) do
if v ~= b then
local dif = b.Position-v.Position
local force = 0
if b.Parent:findFirstChild(v.Name) then -- if b is conneted to v
force = (dif.magnitude-30)/100
else
force = force - 1/dif.magnitude^2
end
local add = dif/dif.magnitude*force
add = add - v.Position/v.Position.magnitude/100
v.velocity.Value = v.velocity.Value + add
end
end
v.CFrame = v.CFrame + v.velocity.Value -- Postion the node
v.velocity.Value = v.velocity.Value*.2 -- Damping
v.CFrame = v.CFrame-v.CFrame.p*Vector3.new(0,1,0) -- Force 2D (optional)
v.Parent.Torso.CFrame = v.CFrame -- To display links connecting nodes
end
end
I found the problem. "b.Parent:findFirstChild(v.Name)" should have been "b.Parent:findFirstChild(v.Parent.Name)," otherwise it will just return true every time. This is just because of how I have the display of the nodes set up.