AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 77295190
Accepted
ChenZX
ChenZX
Asked: 2023-10-15 11:13:05 +0800 CST2023-10-15 11:13:05 +0800 CST 2023-10-15 11:13:05 +0800 CST

Definir limite para widget de entrada em campo real

  • 772

Olá a todos:

Gostaria de definir o limite para o valor de entrada no widget realfield. O código abaixo criará um widget de campo real e o limite do valor de entrada está entre 0 e 0,05.

Se você inserir 0,06 dentro do widget e clicar em algum lugar fora da GUI, ele avisará que não é um valor correto e redefinirá o valor para o último valor.

Mas se você inserir 0,05, ele não irá avisá-lo. E então, se você inserir qualquer outro valor, será exibido "Arquivo de configuração incorreto".

Verifiquei novamente a lógica e não encontrei nenhum código errado. Alguém poderia me ajudar a depurar? Muito obrigado.

Cumprimentos

Chen ZX

Number get_tag_as_number(TagGroup tg, String tag_path, String tag_type, Number low_limit, Number high_limit)
{
    Number tag_value, tag_is_valid
    if (tag_type == "Boolean") tag_is_valid = tg.TagGroupGetTagAsBoolean(tag_path, tag_value)
    if (tag_type == "Number") tag_is_valid = tg.TagGroupGetTagAsNumber(tag_path, tag_value)
    if (!tag_is_valid)
    {
        Result("ERROR: Can not get tag value of " + tag_path + "." + "\n")
        ShowAlert("Can not get tag value of " + tag_path + ".", 0)
        Exit(0)
    }

    if (tag_value < low_limit || tag_value > high_limit)
    {
        Result("ERROR: Wrong config file, " + tag_path + "." + "\n")
        ShowAlert("Wrong config file, " + tag_path + ".", 0)
        Exit(0)
    }
    return tag_value
}

Class testUI : UIFrame
{
    TagGroup ui_config_tg
    Void tg_init(Object self)
    {
        ui_config_tg = NewTagGroup()
        ui_config_tg.TagGroupSetTagAsFloat("display_font:init_value", 0.015)
    }
    TagGroup create_realfield_widget(Object self)
    {
        Number low_limit = 0
        Number high_limit = 0.05
        Number init_value = get_tag_as_number(ui_config_tg, "display_font:init_value", "Number", low_limit, high_limit)
        TagGroup realfield_widget
        realfield_widget = DLGCreateRealField(init_value, 16, 3, "action")
        realfield_widget.DLGIdentifier("#realfield_widget")

        return realfield_widget
    }
    Void action(Object self, TagGroup item_tag)
    {
        Number low_limit = 0
        Number high_limit = 0.05
        Number curr_value = item_tag.DLGGetValue()
        Number init_value
        init_value = get_tag_as_number(ui_config_tg, "display_font:init_value", "Number", low_limit, high_limit)



        if (curr_value < low_limit || curr_value > high_limit)
        {
            OKDialog("Font size must between " + low_limit + " to " + high_limit)
            self.LookUpElement("#realfield_widget").DLGValue(init_value)
            item_tag.DLGValue(init_value)
            Exit(0)
        }
        ui_config_tg.TagGroupSetTagAsFloat("display_font:init_value", curr_value)
        Result( curr_value)
    }
    
    TagGroup create_dialog(Object self)
    {
        self.tg_init()
        TagGroup realfield_widget = self.create_realfield_widget()
                
        TagGroup tabs = DLGCreateTabList()
        tabs.DLGAddElement(realfield_widget)
        TagGroup dialog = DLGCreateDialog("test")
        dialog.DLGAddElement(tabs)
        return dialog
    }
    
    
    testUI(Object self)
    {

        self.init(self.create_dialog())
        self.Display("test")

    }
}

Alloc(testUI)
dm-script
  • 1 1 respostas
  • 11 Views

1 respostas

  • Voted
  1. Best Answer
    BmyGuest
    2023-10-15T18:01:56+08:002023-10-15T18:01:56+08:00

    A lógica é boa, mas você está enfrentando problemas de arredondamento que são particularmente difíceis de detectar em linguagens de script com conversões automáticas de números e strings.

    • DM-Script numberé tratado internamente como duplo (pelo menos no GMS 3)
    • Quando você escreve o valor nas tags como float, você perde precisão.

    É mais seguro seguir em frente ...asNumberpara evitar esses problemas. Você precisa ser específico do tipo apenas nos casos em que for importante, como streaming para um fluxo binário.

    Veja o exemplo a seguir

    number tag_value = 0.05
    number low_limit = 0
    number high_limit = 0.05
    
    clearresults()
    Result("\n Limits are (double):")
    result("\n: low limit:  "+low_limit)
    result("\n: high limit: "+high_limit)
    
    Result("\n Tag value is (double):")
    result("\n tag value:  "+Format(tag_value,"%20.12f"))
    Result("\n (tag_value - low_limit) : "+(tag_value - low_limit))
    Result("\n (tag_value - high_limit): "+(tag_value - high_limit))
    
    taggroup tg = newTagGroup()
    
    tg.TagGroupSetTagAsNumber("Test",tag_value)
    tg.TagGroupGetTagAsNumber("Test",tag_value)
    
    Result("\n ~~~~~ Now with Tag read & write as NUMBER (internally this is DOUBLE)")
    result("\n tag value:  "+Format(tag_value,"%20.12f"))
    Result("\n (tag_value - low_limit) : "+(tag_value - low_limit))
    Result("\n (tag_value - high_limit): "+(tag_value - high_limit))
    
    tg.TagGroupSetTagAsDouble("Test",tag_value)
    tg.TagGroupGetTagAsDouble("Test",tag_value)
    
    Result("\n ~~~~~ Now with Tag read & write as DOUBLE")
    result("\n tag value:  "+Format(tag_value,"%20.12f"))
    Result("\n (tag_value - low_limit) : "+(tag_value - low_limit))
    Result("\n (tag_value - high_limit): "+(tag_value - high_limit))
    
    tg.TagGroupSetTagAsFloat("Test",tag_value)
    tg.TagGroupGetTagAsFloat("Test",tag_value)
    
    Result("\n ~~~~~ Now with Tag read & write as FLOAT")
    result("\n tag value:  "+Format(tag_value,"%20.12f"))
    Result("\n (tag_value - low_limit) : "+(tag_value - low_limit))
    Result("\n (tag_value - high_limit): "+(tag_value - high_limit))
    

    Como alternativa, você pode corrigir seu script não verificando exatamente "0", mas sim um pequeno valor épsilon que explica o problema de precisão:

    [...]
        number eps = 1e-9
        if ((tag_value - low_limit)< eps || (tag_value - high_limit) > eps)
        {
            Result("ERROR: Wrong config file, " + tag_path + "." + "\n")
            ShowAlert("Wrong config file, " + tag_path + ".", 0)
            Exit(0)
        }
    
    • 1

relate perguntas

  • É possível usar uma classe para definir uma guia na UI?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve