I'm working on a block coding engine in Roblox, I have some blocks made like move, change size and rotate. But I can't figure out how to make a loop, I have to find every item between two items in a for i,v in pairs loop.
for i, block in pairs(script.Parent.Parent.Script:GetChildren()) do
wait(0.1)
if block.Value == "MoveX" then
game.Character.Position = UDim2.new(game.Character.Position.X.Scale, (game.Character.Position.X.Offset + block.EpicValue.Value), game.Character.Position.X.Scale, game.Character.Position.Y.Offset)
end
if block.Value == "MoveY" then
game.Character.Position = UDim2.new(game.Character.Position.X.Scale, game.Character.Position.X.Offset, game.Character.Position.X.Scale, (game.Character.Position.Y.Offset + block.EpicValue.Value))
end
if block.Value == "Rotate" then
game.Character.Rotation = game.Character.Rotation + block.EpicValue.Value
end
if block.Value == "SizeX" then
game.Character.Size = UDim2.new(game.Character.Size.X.Scale, math.abs(block.EpicValue.Value), game.Character.Size.X.Scale, game.Character.Size.Y.Offset)
end
if block.Value == "SizeY" then
game.Character.Size = UDim2.new(game.Character.Size.X.Scale, game.Character.Size.X.Offset, game.Character.Size.Y.Scale, math.abs(block.EpicValue.Value))
end
if block.Value == "LoopStart" then
-- start loop
end
end
Instead of a foreach loop, use a while loop. Then you can easily convert this while loop into a state machine:
local i = 1
local instructions = script.Parent.Parent.Script:GetChildren()
while i < #instructions do
-- fetch current instruction
local block = instructions[i]
if block.Value == "MoveX" then
--...
elseif block.Value == "LoopStart" then
if not insertYourLoopCondition then
i = instructionIndexOfLoopEnd
end
elseif block.Value == "LoopEnd" then
i = instructionIndexOfLoopStart - 1
end
-- next instruction
i = i + 1
end
In words: you need jumps. A loop consists of a condition and a "jump" at the end to return to the condition.
A condition is a "conditional jump".
When generating your blocks you need to gather the target indices of all jumps once.
I tried to fix some Garry's Mod addon and this is what happens. I tried to fix it for long time, but I'm not the best in Lua coding :/ . What is wrong with this code? I get this error:
[ERROR] addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80: bad argument #1 to 'SetPhysicsAttacker' (Entity expected, got nil)
1. SetPhysicsAttacker - [C]:-1
2. unknown - addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80
And the code is pretty long. I have every file working fine, but this file is not working
AddCSLuaFile()
DEFINE_BASECLASS( "base_anim" )
if (SERVER) then
util.AddNetworkString( "gb5_net_sound_lowsh" )
end
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.PrintName = ""
ENT.Author = ""
ENT.Contact = ""
ENT.GBOWNER = nil
ENT.MAX_RANGE = 0
ENT.SHOCKWAVE_INCREMENT = 0
ENT.DELAY = 0
ENT.SOUND = ""
net.Receive( "gb5_net_sound_lowsh", function( len, pl )
local sound = net.ReadString()
LocalPlayer():EmitSound(sound)
end );
function ENT:Initialize()
if (SERVER) then
self.FILTER = {}
self:SetModel("models/props_junk/watermelon01_chunk02c.mdl")
self:SetSolid( SOLID_NONE )
self:SetMoveType( MOVETYPE_NONE )
self:SetUseType( ONOFF_USE )
self.Bursts = 0
self.CURRENTRANGE = 0
self.GBOWNER = self:GetVar("GBOWNER")
self.SOUND = self:GetVar("SOUND")
end
end
function ENT:Think()
if (SERVER) then
if not self:IsValid() then return end
local pos = self:GetPos()
self.CURRENTRANGE = self.CURRENTRANGE+(self.SHOCKWAVE_INCREMENT*10)
if(GetConVar("gb5_realistic_sound"):GetInt() >= 1) then
for k, v in pairs(ents.FindInSphere(pos,self.CURRENTRANGE)) do
if v:IsPlayer() then
if not (table.HasValue(self.FILTER,v)) then
net.Start("gb5_net_sound_lowsh")
net.WriteString(self.SOUND)
net.Send(v)
v:SetNWString("sound", self.SOUND)
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
if GetConVar("gb5_sound_shake"):GetInt()== 1 then
util.ScreenShake( v:GetPos(), 5555, 555, self.shocktime, 500 )
end
table.insert(self.FILTER, v)
end
end
end
else
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
local ent = ents.Create("gb5_shockwave_sound_instant")
ent:SetPos( pos )
ent:Spawn()
ent:Activate()
ent:SetPhysicsAttacker(ply)
ent:SetVar("GBOWNER", self.GBOWNER)
ent:SetVar("MAX_RANGE",50000)
ent:SetVar("DELAY",0.01)
ent:SetVar("Shocktime",self.shocktime)
ent:SetVar("SOUND", self:GetVar("SOUND"))
self:Remove()
end
self.Bursts = self.Bursts + 1
if (self.CURRENTRANGE >= self.MAX_RANGE) then
self:Remove()
end
self:NextThink(CurTime() + (self.DELAY*10))
return true
end
end
function ENT:OnRemove()
if SERVER then
if self.FILTER==nil then return end
for k, v in pairs(self.FILTER) do
if not v:IsValid() then return end
v:SetNWBool("waiting", true)
end
end
end
function ENT:Draw()
return false
end
Is there a chance someone fix this for me? Or even just telling me what's wrong? I would be pleased. If needed I can send all files. Well... It's not my addon but I'm trying to fix an existing one. Someone tried to fix it too but he didn't (actually he broke it even more).
What the error means
Inside your ENT:Think() function, you are calling ent:SetPhysicsAttacker(ply)
ply is not defined anywhere inside that function, so is nil (Entity expected, got nil)
How to fix this
If no player is responsible for the damage caused by this entity, delete the line ent:SetPhysicsAttacker(ply).
Otherwise, assign an Owner to the entity at the point of creation, using SetOwner.
This would then allow you to use self:GetOwner() inside your Think hook
Example
hook.Add("PlayerSay", "SpawnEntity", function(ply, text)
if string.lower(text) == "!spawnentity" then
-- Create your entity
local myEntity = ents.Create("gb5_shockwave_sound_lowsh")
myEntity:SetPos(ply:GetPos())
myEntity:SetAngles(ply:GetAngles())
myEntity:Spawn()
-- Sets the owner to the player that typed the command
myEntity:SetOwner(ply)
return ""
end
end)
-- Inside your entity code
function ENT:Think()
print("My owner is: " .. tostring(self:GetOwner()))
-- ...
ent:SetPhysicsAttacker(self:GetOwner())
end
I'm creating a program for a turtle in ComputerCraft. The program is going to make the turtle control a warehouse of storage for my items in the game. It will check what item I put in, then it will figure out the chest's location, go there, and dump it in. I am storing the locations of each chest in a table. For example:
cobblestone = {2,0,1}
That tells the turtle that the cobblestone chest is stored at position x=2 y=0 and z=1. To get the turtle to tell what it needs to store, it does:
itemDetails = turtle.getItemDetail()
name = string.gsub(itemDetails.name, "minecraft:", "")
This gets the turtle to get the details of the item. It then sets a variable to be the name of the item minus the minecraft: at the beginning of it (I can't have a variable called "minecraft:cobblestone"). I don't know how to use this variable to call the table and find its position for the turtle to go to it. If anybody can help, I would appreciate any of the help. Thanks in advance!
Also, just a heads up, the code is still set up for debugging and testing purposes. The setup is a turtle, with an input chest in front of it, a fuel chest to the right, and the warehouse behind it.
I've tried doing:
cobblestone = {2,0,1}
--Putting a piece of cobblestone in--
itemDetails = turtle.getItemDetail()
--Returning name of "minecraft:cobblestone"--
name = string.gsub(itemDetails.name, "minecraft:", "")
print name[1]
So far this hasn't worked.
pos = {0,0,0}
looking = 0
cobblestone = {2,0,1}
function fuel()
if turtle.getFuelLevel() < 20 then
turtle.select(16)
turtle.refuel(1)
end
end
function left()
turtle.turnLeft()
looking = looking - 1
if looking < 0 then
looking = 3
end
print(looking)
end
function right()
turtle.turnRight()
looking = looking + 1
if looking > 3 then
looking = 0
end
print(looking)
end
function forward()
fuel()
if turtle.forward() then
if looking == 0 then
pos[1] = pos[1] - 1
elseif looking == 1 then
pos[3] = pos[3] - 1
elseif looking == 2 then
pos[1] = pos[1] + 1
elseif looking == 3 then
pos[3] = pos[3] + 1
else
print("wot")
end
end
end
function up()
fuel()
turtle.up()
pos[2] = pos[2] + 1
end
function down()
fuel()
turtle.down()
pos[2] = pos[2] - 1
end
function goHome()
while pos[3] > 0 do
while looking > 1 do
left()
end
forward()
end
while pos[2] > 0 do
down()
end
while pos[1] > 0 do
while looking > 0 do
left()
end
forward()
end
end
while true do
turtle.select(1)
while not turtle.suck() do
sleep(1)
end
itemDetails = turtle.getItemDetail()
name = string.gsub(itemDetails.name, "minecraft:", "")
print(name)
while looking < 2 or looking > 2 do
left()
end
for i = pos[1],name[1]-1 do
forward()
end
while looking > 3 or looking < 3 do
right()
end
for i = pos[3],name[3]-1 do
forward()
end
for i = pos[2],name[2]-1 do
up()
end
while looking < 2 or looking > 2 do
left()
end
turtle.select(1)
turtle.drop()
goHome()
end
I want to be able to do:
cobblestone = {2,0,1}
--Putting a piece of cobblestone in--
itemDetails = turtle.getItemDetail()
--Returning name of "minecraft:cobblestone"--
name = string.gsub(itemDetails.name, "minecraft:", "")
print name[1]
and have the turtle print the same thing as
cobblestone[1]
which would be 2. However, it returns with nil.
Currently, your cobblestone is global, what is bad for this example. At first, store all elements like this:
local myelems = {
cobblestone = {2,0,1};
grass = {3,1,2};
}
and so on. Use local variables when you can, it's good practice in programming at all.
So let's look at your code:
-- Returning name of "minecraft:cobblestone"
local name = string.gsub(itemDetails.name, "minecraft:", "")
print(name[1])
What it does? (I've changed it a bit)
At first,string.gsub look like an overkill here, use string.match instead:
local name = itemDetails.name:match("^minecraft:(.+)$")
Here itemDetails.name:match is same as calling string.match with itemDetails.name as first argument. It can be used for all string functions.
So here name is string variable. Indexing strings in different languages may have different results. In lua in actually provide access to all string functions to make calls to them easier (as above). There is no such function as string[1], so you get nil. However, now we have table myelems in which keys are strings and values are your tables.
Full code:
-- Table for all elements
local myelems = {
cobblestone = {2,0,1};
grass = {3,1,2};
}
-- Putting a piece of cobblestone in
local itemDetails = turtle.getItemDetail()
--Returning name of "minecraft:cobblestone"
local name = itemDetails.name:match("^minecraft:(.+)$")
-- Get our table
local elem = myelems[name]
if elem then
print(elem[1], elem[2], elem[3])
end
I'm trouble to understand self and local value.
Here is my asteroid.lua. I created local asteroid inside :create and was trying to use it other function but it is not working correctly.
-- Class Declaration
Asteroid = {}
Asteroid.__index = Asteroid
function Asteroid:create()
local asteroid = {}
setmetatable(asteroid, Asteroid)
-- Animation Data
asteroid.frames = {}
asteroid.currentFrame = 1
asteroid.frameDuration = 0.04 -- 0.016
asteroid.frameTimeRemaining = asteroid.frameDuration
asteroid.x = 0
asteroid.y = 0
return asteroid
end
function Asteroid:init()
-- Use a loop to load a bunch of files!
for index= 0, 15 do
-- Use logic to build the filename...
file = 'art/large/a100'
-- Take into account the extra 0
if index < 10 then
file = file .. '0'
end
-- Add the file number and then .png
file = file .. tostring(index) .. '.png'
-- Load the file... (we'll use lua's 1 index to be kind)
self.frames[index + 1] = love.graphics.newImage(file)
if self.frames[index + 1] ~= nil then
print('Loaded frame ' .. tostring(index + 1))
end
end
-- Set the velocity randomly!
self.velocity = {}
self.velocity.x = math.random(-76.0, 76.0)
self.velocity.y = math.random(-76.0, 76.0)
end
Asteroid.updateAnimation = function(deltaTime)
-- Catch variable into 'easy-to-type' one
local ftr = Asteroid.frameTimeRemaining
THIS PART(local ftr) IS MY PROBLEM: ATTEMPT TO INDEX A NIL VALUE.
I tried different ways like self.frameTimeRemaing but I couldn't figure out.
Is anyone know how I can fix this local?
-- Subtract time
ftr = ftr - deltaTime
-- If the frame is over...
if ftr < 0 then
Asteroid.nextFrame()
Asteroid.frameTimeRemaining = Asteroid.frameDuration
else
Asteroid.frameTimeRemaining = ftr
end
end
Without seeing the rest of the code, I can only guess. Try this:
function Asteroid:updateAnimation(deltaTime)
-- use self instead of Asteroid in this function
end
I have a motorized roller blind project.
I am following this instructable: https://www.instructables.com/id/Motorized-WiFi-IKEA-Roller-Blind/ .
I am using the code in the instructable, but I suspect tha fault is in one of these codes:
config.lua
-- file : config.lua
local module = {}
module.SSID = {}
module.SSID["ssid"] = "password"
-- example for local MQTT
--module.MQHOST = "ohab.local"
--module.MQPORT = 1883
--module.MQID = node.chipid()
--module.MQUSR = ""
--module.MQPW = ""
-- example for cloud MQTT
module.MQHOST = "192.***.*.*"
module.MQPORT = 1883
module.MQID = node.chipid()
module.MQUSR = "username"
module.MQPW = "password"
module.MQTLS = 1 -- 0 = unsecured, 1 = TLS/SSL
module.ENDPOINT = "/house/masterbedroom/rollerblind/"
module.ID = "0"
--module.SUB = "set"
module.SUB = {[module.ENDPOINT .. module.ID .. "/set"]=0,[module.ENDPOINT .. "all"]=0}
module.POST = module.ENDPOINT .. module.ID .. "/status"
return module
wifi_setup
-- file: setup.lua
local module = {}
local function wifi_wait_ip()
if wifi.sta.getip()== nil then
print("IP unavailable, Waiting...")
else
tmr.stop(1)
gpio.write(pin_led,1) --off
print("\n================== ==================")
print("ESP8266 mode is: " .. wifi.getmode())
print("MAC address is: " .. wifi.ap.getmac())
print("IP is "..wifi.sta.getip())
print("====================================")
mq.start()
end
end
local function wifi_start(list_aps)
if list_aps then
gpio.write(pin_led,0) --on
for key,value in pairs(list_aps) do
if config.SSID and config.SSID[key] then
wifi.setmode(wifi.STATION);
wifi.sta.config(key,config.SSID[key])
wifi.sta.connect()
print("Connecting to " .. key .. " ...")
--config.SSID = nil -- can save memory
tmr.alarm(1, 2500, 1, wifi_wait_ip)
end
end
else
print("Error getting AP list")
end
end
function module.start()
print("Configuring Wifi ...")
wifi.setmode(wifi.STATION);
wifi.sta.getap(wifi_start)
end
return module
Sadly I cant manage to go beyond step 4. After I have tried to download the code to the ESP8266 I only get this error:
PANIC: unprotected error in call to Lua API (wifi_setup.lua:25: bad argument #1 to 'config' (config table not found!))
I have only changed the stuff the instructable told me to change, and I have tried to look for faults myself but I cant find any... It's the first time I am using Lua, so this is totally new for me.
Hope somebody here can offer some help. Been stuck on this for days...
THIS PART OF THE PROBLEM IS SOLVED. CHECK COMMENTS FOR SOLUTION
Sadly when one problem is solved, a new one rises...
The chip is now successfully connecting to the wifi and mqtt service, but when I try to do the dry run by putting in the command 'step_move(1000,FWD,2)' nothing happens. The motor should rotate...
Also when I press the button I get a new panic error as follows:
PANIC: unprotected error in call to Lua API (button.lua:23: attempt to perform arithmetic on upvalue '?' (a nil value))
button.lua
--file button4.lua
do
-- use pin 1 as the input pulse width counter
local pin=5
local debounce = 150 --ms
local longpress = 2000 --ms
local pulse1, pulse2, du, now, trig = 1, 0, 0, tmr.now, gpio.trig
local prev_int_time, int_time, up_time = 0
local cal_steps = 100000
local cal_steps_dn = 0
local cal_steps_up = 0
local cal_state = 0 -- 0 = not calibration, 1 = calibrating down, 2 = calibrating up
state = 0 -- state: 0 = up, 1 = transition, 2 = down
gpio.mode(pin,gpio.INT)
local function pin4cb(level)
int_time = now() / 1000
if ((int_time - prev_int_time) > debounce) then
if (level == 0) then
up_time = int_time
else
if((int_time - up_time) > longpress) then
print("calibrating")
cal_state = 1
--cur_step = 100000
step_move(cal_steps,FWD,2)
else -- short press
print("short", cal_state)
if (cal_state == 2) then -- calibrated up (done)
print("calibration done")
state = 0 -- up
cur_step = 0
tot_steps = cal_steps - step_stepsleft
print("cal_steps: " .. cal_steps)
print("step_stepsleft: " .. step_stepsleft)
print("tot_steps: " .. tot_steps)
step_stop()
pins_disable()
cal_state = 0
if file.open("cfg_tot_steps.lua", "w+") then
file.write("tot_steps=" .. tot_steps .. '\n')
file.close()
end
elseif (cal_state == 1) then -- calibrated dn (switch direction)
print("calibration low point")
print(cal_steps - step_stepsleft)
step_stop()
step_move(cal_steps,REV,2)
cal_state = 2
elseif (cal_state == 0) then
if (state == 0 and step_stepsleft == 0) then -- i am up, go dowm
rollerblind.down()
-- state = 2
elseif (state == 1) then -- i am moving, do nothing
-- do nothing
elseif (state == 2 and step_stepsleft == 0) then -- i am down, go up
rollerblind.up()
-- state = 0
end
end
end
end
--print (level)
prev_int_time = int_time
end
end
gpio.trig(pin, "both", pin4cb)
end
Here is the code for the stepper.lua:
-- stepper.lua
-- code from: http://www.esp8266.com/viewtopic.php?f=19&t=2326
-- simple stepper driver for controlling a stepper motor with a
-- l293d driver
-- nodemcu pins: 0 5 6 7
stepper_pins = {1,3,2,4} -- (A-)blue, (A+)pink, (B-)yellow, (B+)orange
--stepper_pins = {1,2,3,4}
-- half or full stepping
step_states4 = {
{1,0,0,1},
{1,1,0,0},
{0,1,1,0},
{0,0,1,1}
}
step_states8 = {
{1,0,0,0},
{1,1,0,0},
{0,1,0,0},
{0,1,1,0},
{0,0,1,0},
{0,0,1,1},
{0,0,0,1},
{1,0,0,1},
}
step_states = step_states4 -- choose stepping mode
step_numstates = 4 -- change to match number of rows in step_states
step_delay = 10 -- choose speed
step_state = 0 -- updated by step_take-function
step_direction = 1 -- choose step direction -1, 1
step_stepsleft = 0 -- number of steps to move, will de decremented
step_timerid = 4 -- which timer to use for the steps
status_timerid = 2 -- timer id for posing of status messages
-- setup pins
function pins_enable()
for i = 1, 4, 1 do
gpio.mode(stepper_pins[i],gpio.OUTPUT)
end
end
function pins_disable()
-- for i = 1, 4, 1 do -- no power, all pins
for i = 2, 4, 1 do -- no power, all pins except one (to keep it in place)
gpio.mode(stepper_pins[i],gpio.INPUT)
end
end
-- turn off all pins to let motor rest
function step_stopstate()
for i = 1, 4, 1 do
gpio.write(stepper_pins[i], 0)
end
end
-- make stepper take one step
function step_take()
-- jump to the next state in the direction, wrap
step_state = step_state + step_direction
cur_step = cur_step + step_direction * FWD
if step_state > step_numstates then
step_state = 1;
elseif step_state < 1 then
step_state = step_numstates
end
-- write the current state to the pins
pins_enable()
for i = 1, 4, 1 do
gpio.write(stepper_pins[i], step_states[step_state][i])
end
-- might take another step after step_delay
step_stepsleft = step_stepsleft-1
if step_stepsleft > 0 then
-- if cur_step > 0 and cur_step < tot_steps and step_stepsleft > 0 then
tmr.alarm(step_timerid, 10, 0, step_take )
--tmr.alarm(step_timerid, 10, 0, step_take )
else
step_stopstate()
step_stop()
pins_disable()
mq.post_status()
if file.open("cfg_cur_step.lua", "w+") then
file.write("cur_step=" .. cur_step .. '\n')
file.close()
end
end
end
-- public method to start moving number of 'int steps' in 'int direction'
function step_move(steps, direction, delay)
tmr.stop(step_timerid)
step_stepsleft = steps
step_direction = direction
step_delay = delay
step_take()
end
function step_go_to(step, delay)
if step >= cur_step then
steps = step - cur_step
step_move(steps, FWD, delay)
end
if step <= cur_step then
steps = cur_step - step
step_move(steps, REV, delay)
end
end
function percent_go_to(percent, delay)
if(percent >= 0 and percent <= 100) then
step_stop()
tmr.register(status_timerid, 1000, tmr.ALARM_AUTO, function () mq.post_status() end)
tmr.start(status_timerid)
step = percent * tot_steps / 100
step_go_to(step, delay)
end
end
-- public method to cancel moving
function step_stop()
tmr.stop(step_timerid)
tmr.stop(status_timerid)
step_stepsleft = 0
step_stopstate()
end
Let's parse the error message one by one:
unprotected error in call to Lua API (wifi_setup.lua:25: bad argument #1 to 'config' (config table not found!))
Unprotected error means that you did a normal function call, as opposed to a protected call (aka pcall), which is a function call where you expect errors to occur and want to provide means to handle them. Since you did not do a protected call, Lua does not know how to handle the error and terminates right away (which is not a bad thing).
wifi_setup.lua:25 tells you the file and line at which the error occured.
bad argument #1 to 'config' means that the problem is due to the first argument passed to a function named config.
config table not found! is the error message provided by the implementer of that function.
So in summary, there is a problem with the function call wifi.sta.config(key,config.SSID[key]) as it expects a table as first argument, while you provided something different (ie. a string with the BSSID). Indeed checking with the NodeMCU docs shows that you need to pass a table to this function:
wifi.sta.config()
Sets the WiFi station configuration. [...]
Syntax
wifi.sta.config(station_config)
Parameters
station_config table containing configuration data for
station
The expected layout of the table is documented in detail on that page as well.
ComicSansMS provided a great answer the essence of which is that you need to replace
wifi.sta.config(key,config.SSID[key])
with
wifi.sta.config{ssid=key,pwd=config.SSID[key]}
Thus a standalone example could be like this:
--wifi.setmode(wifi.NULLMODE)
config = {}
config.SSID = {}
config.SSID["ssid"] = "password"
function wifi_wait_ip()
if wifi.sta.getip() == nil then
print("IP unavailable, Waiting...")
else
tmr.stop(1)
print("\n====================================")
print("ESP8266 mode is: " .. wifi.getmode())
print("MAC address is: " .. wifi.ap.getmac())
print("IP is " .. wifi.sta.getip())
print("====================================")
end
end
function wifi_start(list_aps)
if list_aps then
for key, value in pairs(list_aps) do
if config.SSID and config.SSID[key] then
wifi.setmode(wifi.STATION);
wifi.sta.config{ssid=key, pwd=config.SSID[key]}
-- wifi.sta.connect() not needed as config() uses auto-connect=true by default
print("Connecting to " .. key .. " ...")
tmr.alarm(1, 2500, 1, wifi_wait_ip)
end
end
else
print("Error getting AP list")
end
end
function start()
print("Configuring Wifi ...")
wifi.setmode(wifi.STATION)
wifi.sta.getap(wifi_start)
end
start()