checkboxes and errors

I get an error like:
attempt to index a boolean value

local function musicF( event )
      local switch = event.target
      if switch.isOn == true then
        music = true
      else
        music = false
      end
  end

  local musicW = widget.newSwitch(
      {
          left = 250,
          top = 200,
          style = "checkbox",
          id = "Checkbox",
          onPress = musicF
      }
  )

  sceneGroup:insert(musicW)

  if music == true then
    musicW:setState(true)
  else
    musicW:setState(false)
  end

At that point in the code, music hasn’t been defined or set.

Just add this to the top of that code:

local music = false

e.g.

local music = false
local function musicF( event )
      local switch = event.target
      if switch.isOn == true then
        music = true
      else
        music = false
      end
  end

  local musicW = widget.newSwitch(
      {
          left = 250,
          top = 200,
          style = "checkbox",
          id = "Checkbox",
          onPress = musicF
      }
  )

  sceneGroup:insert(musicW)

  if music == true then
    musicW:setState(true)
  else
    musicW:setState(false)
  end

Question, didn’t the error message complain about this line by line number?
if music == true then

oh, forgot to mention what error hapens on that musicW:setState(true)

And music is global variable which is loaded at main.lua

That sounds strange if musicW is indeed a widget as your code suggests. Are you sure you haven’t accidentally called music:setState(true) instead? Maybe you can post the stack trace from your error to help us help you?

Oh, and a little tip to help you write shorter and cleaner code is to not do boolean comparisons and assignments like this:

  if switch.isOn == true then
    music = true
  else
    music = false
  end

and this:

  if music == true then
    musicW:setState(true)
  else
    musicW:setState(false)
  end

Instead, you can just write:

music = switch.isOn

and

musicW:setState(music)

Thanks for tip!

And I think I maybe using set state wrong way.

Yes I used setState() wrong way