oniksan / godobuf

A Google Protobuf implementation for Godot / GDScript
BSD 3-Clause "New" or "Revised" License
260 stars 36 forks source link

Add has_ function for optionals #42

Closed cmdrk closed 3 months ago

cmdrk commented 7 months ago

Optional fields can return null if they are not present. Since the function is typed, and Godot currently has no nullable static types per https://github.com/godotengine/godot-proposals/issues/162, this can fail. I propose adding a "has_" method if the field is optional.

e.g.. This fails:

var mass = obj.get_mass() 

with the following error if the field is not set in the protobuf message: Trying to return value of type "Nil" from a function which the return type is "float".

because get_mass() is defined as:

func get_mass() -> float:
    return _mass.value

which cannot return nil.

This patch introduces a new function to generate, e.g.:

func has_mass() -> bool:
    if _mass.value != null:
        return true
    return false

So callers can check if the field is set before attempting to get the value.